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_spec.name = servable_name request.inputs["input"].CopyFrom( tf.make_tensor_proto( [ex.SerializeToString() for ex in examples], shape=[len(examples)])) response = stub.Predict(request, timeout_secs) outputs = tf.make_ndarray(response.outputs["outputs"]) scores = tf.make_ndarray(response.outputs["scores"]) assert len(outputs) == len(scores) return [{ # pylint: disable=g-complex-comprehension "outputs": output, "scores": score } for output, score in zip(outputs, scores)] return _make_grpc_request
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_spec.name = servable_name request.inputs["input"].CopyFrom( tf.make_tensor_proto( [ex.SerializeToString() for ex in examples], shape=[len(examples)])) response = stub.Predict(request, timeout_secs) outputs = tf.make_ndarray(response.outputs["outputs"]) scores = tf.make_ndarray(response.outputs["scores"]) assert len(outputs) == len(scores) return [{ # pylint: disable=g-complex-comprehension "outputs": output, "scores": score } for output, score in zip(outputs, scores)] return _make_grpc_request
[ "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.\"\"\"", "request", "=", "predict_pb2", ".", "PredictRequest", "(", ")", "request", ".", "model_spec", ".", "name", "=", "servable_name", "request", ".", "inputs", "[", "\"input\"", "]", ".", "CopyFrom", "(", "tf", ".", "make_tensor_proto", "(", "[", "ex", ".", "SerializeToString", "(", ")", "for", "ex", "in", "examples", "]", ",", "shape", "=", "[", "len", "(", "examples", ")", "]", ")", ")", "response", "=", "stub", ".", "Predict", "(", "request", ",", "timeout_secs", ")", "outputs", "=", "tf", ".", "make_ndarray", "(", "response", ".", "outputs", "[", "\"outputs\"", "]", ")", "scores", "=", "tf", ".", "make_ndarray", "(", "response", ".", "outputs", "[", "\"scores\"", "]", ")", "assert", "len", "(", "outputs", ")", "==", "len", "(", "scores", ")", "return", "[", "{", "# pylint: disable=g-complex-comprehension", "\"outputs\"", ":", "output", ",", "\"scores\"", ":", "score", "}", "for", "output", ",", "score", "in", "zip", "(", "outputs", ",", "scores", ")", "]", "return", "_make_grpc_request" ]
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 = "projects/%s/models/%s/versions/%s" % (cloud.default_project(), model_name, version) input_data = { "instances": [{ # pylint: disable=g-complex-comprehension "input": { "b64": base64.b64encode(ex.SerializeToString()) } } for ex in examples] } prediction = api.projects().predict(body=input_data, name=parent).execute() return prediction["predictions"] return _make_cloud_mlengine_request
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 = "projects/%s/models/%s/versions/%s" % (cloud.default_project(), model_name, version) input_data = { "instances": [{ # pylint: disable=g-complex-comprehension "input": { "b64": base64.b64encode(ex.SerializeToString()) } } for ex in examples] } prediction = api.projects().predict(body=input_data, name=parent).execute() return prediction["predictions"] return _make_cloud_mlengine_request
[ "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", "(", "\"ml\"", ",", "\"v1\"", ",", "credentials", "=", "credentials", ")", "parent", "=", "\"projects/%s/models/%s/versions/%s\"", "%", "(", "cloud", ".", "default_project", "(", ")", ",", "model_name", ",", "version", ")", "input_data", "=", "{", "\"instances\"", ":", "[", "{", "# pylint: disable=g-complex-comprehension", "\"input\"", ":", "{", "\"b64\"", ":", "base64", ".", "b64encode", "(", "ex", ".", "SerializeToString", "(", ")", ")", "}", "}", "for", "ex", "in", "examples", "]", "}", "prediction", "=", "api", ".", "projects", "(", ")", ".", "predict", "(", "body", "=", "input_data", ",", "name", "=", "parent", ")", ".", "execute", "(", ")", "return", "prediction", "[", "\"predictions\"", "]", "return", "_make_cloud_mlengine_request" ]
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, input_encoder, add_eos=problem.has_inputs) for inputs in inputs_list ] examples = [_make_example(input_ids, problem, fname) for input_ids in input_ids_list] predictions = request_fn(examples) output_decoder = problem.feature_info["targets"].encoder outputs = [ (_decode(prediction["outputs"], output_decoder), prediction["scores"]) for prediction in predictions ] return outputs
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, input_encoder, add_eos=problem.has_inputs) for inputs in inputs_list ] examples = [_make_example(input_ids, problem, fname) for input_ids in input_ids_list] predictions = request_fn(examples) output_decoder = problem.feature_info["targets"].encoder outputs = [ (_decode(prediction["outputs"], output_decoder), prediction["scores"]) for prediction in predictions ] return outputs
[ "def", "predict", "(", "inputs_list", ",", "problem", ",", "request_fn", ")", ":", "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", ",", "input_encoder", ",", "add_eos", "=", "problem", ".", "has_inputs", ")", "for", "inputs", "in", "inputs_list", "]", "examples", "=", "[", "_make_example", "(", "input_ids", ",", "problem", ",", "fname", ")", "for", "input_ids", "in", "input_ids_list", "]", "predictions", "=", "request_fn", "(", "examples", ")", "output_decoder", "=", "problem", ".", "feature_info", "[", "\"targets\"", "]", ".", "encoder", "outputs", "=", "[", "(", "_decode", "(", "prediction", "[", "\"outputs\"", "]", ",", "output_decoder", ")", ",", "prediction", "[", "\"scores\"", "]", ")", "for", "prediction", "in", "predictions", "]", "return", "outputs" ]
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_internal_states = False hparams.add_hparam("num_lstm_layers", 2) hparams.add_hparam("num_lstm_filters", 256) return hparams
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_internal_states = False hparams.add_hparam("num_lstm_layers", 2) hparams.add_hparam("num_lstm_filters", 256) return hparams
[ "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_frames", "=", "4", "hparams", ".", "video_num_target_frames", "=", "4", "hparams", ".", "concat_internal_states", "=", "False", "hparams", ".", "add_hparam", "(", "\"num_lstm_layers\"", ",", "2", ")", "hparams", ".", "add_hparam", "(", "\"num_lstm_filters\"", ",", "256", ")", "return", "hparams" ]
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 FLAGS.cloud_mlengine: return cloud_mlengine.launch() if FLAGS.generate_data: t2t_trainer.generate_data() if cloud_mlengine.job_dir(): FLAGS.output_dir = cloud_mlengine.job_dir() if argv: t2t_trainer.set_hparams_from_args(argv[1:]) hparams.distill_phase = "train" exp_fn = t2t_trainer.create_experiment_fn() exp = exp_fn(run_config, hparams) return exp
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 FLAGS.cloud_mlengine: return cloud_mlengine.launch() if FLAGS.generate_data: t2t_trainer.generate_data() if cloud_mlengine.job_dir(): FLAGS.output_dir = cloud_mlengine.job_dir() if argv: t2t_trainer.set_hparams_from_args(argv[1:]) hparams.distill_phase = "train" exp_fn = t2t_trainer.create_experiment_fn() exp = exp_fn(run_config, hparams) return exp
[ "def", "create_teacher_experiment", "(", "run_config", ",", "hparams", ",", "argv", ")", ":", "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", "FLAGS", ".", "cloud_mlengine", ":", "return", "cloud_mlengine", ".", "launch", "(", ")", "if", "FLAGS", ".", "generate_data", ":", "t2t_trainer", ".", "generate_data", "(", ")", "if", "cloud_mlengine", ".", "job_dir", "(", ")", ":", "FLAGS", ".", "output_dir", "=", "cloud_mlengine", ".", "job_dir", "(", ")", "if", "argv", ":", "t2t_trainer", ".", "set_hparams_from_args", "(", "argv", "[", "1", ":", "]", ")", "hparams", ".", "distill_phase", "=", "\"train\"", "exp_fn", "=", "t2t_trainer", ".", "create_experiment_fn", "(", ")", "exp", "=", "exp_fn", "(", "run_config", ",", "hparams", ")", "return", "exp" ]
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 = len(inputs) if mask_id is None: # TODO(lukaszkaiser): can we just divide the sum by length? XLA optimizes? return sum([np.mean(x) / length for x in inputs]) unmask = [1.0 - np.equal(t, mask_id).astype(np.float32) for t in targets] return sum([np.sum(x * m) / (length * np.sum(m)) for x, m in zip(inputs, unmask)])
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 = len(inputs) if mask_id is None: # TODO(lukaszkaiser): can we just divide the sum by length? XLA optimizes? return sum([np.mean(x) / length for x in inputs]) unmask = [1.0 - np.equal(t, mask_id).astype(np.float32) for t in targets] return sum([np.sum(x * m) / (length * np.sum(m)) for x, m in zip(inputs, unmask)])
[ "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.", "# TODO(lukaszkaiser): remove this assumption (e.g., when masks differ).", "length", "=", "len", "(", "inputs", ")", "if", "mask_id", "is", "None", ":", "# TODO(lukaszkaiser): can we just divide the sum by length? XLA optimizes?", "return", "sum", "(", "[", "np", ".", "mean", "(", "x", ")", "/", "length", "for", "x", "in", "inputs", "]", ")", "unmask", "=", "[", "1.0", "-", "np", ".", "equal", "(", "t", ",", "mask_id", ")", ".", "astype", "(", "np", ".", "float32", ")", "for", "t", "in", "targets", "]", "return", "sum", "(", "[", "np", ".", "sum", "(", "x", "*", "m", ")", "/", "(", "length", "*", "np", ".", "sum", "(", "m", ")", ")", "for", "x", ",", "m", "in", "zip", "(", "inputs", ",", "unmask", ")", "]", ")" ]
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]) xent.append(np.sum(prediction * hot_target, axis=-1)) return masked_mean(xent, targets)
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]) xent.append(np.sum(prediction * hot_target, axis=-1)) return masked_mean(xent, targets)
[ "def", "neg_log_perplexity", "(", "batch", ",", "model_predictions", ")", ":", "_", ",", "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", "]", ")", "xent", ".", "append", "(", "np", ".", "sum", "(", "prediction", "*", "hot_target", ",", "axis", "=", "-", "1", ")", ")", "return", "masked_mean", "(", "xent", ",", "targets", ")" ]
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(target, pred.shape[-1]), axis=-1)) return - masked_mean(xent, targets)
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(target, pred.shape[-1]), axis=-1)) return - masked_mean(xent, targets)
[ "def", "loss", "(", "params", ",", "batch", ",", "model_predict", ",", "rng", ")", ":", "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", "(", "target", ",", "pred", ".", "shape", "[", "-", "1", "]", ")", ",", "axis", "=", "-", "1", ")", ")", "return", "-", "masked_mean", "(", "xent", ",", "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 loaded from %s at step %d" % (params_file, step)) logging.debug("From loaded model : history = %s", history) return State(step=step, params=params, history=history)
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 loaded from %s at step %d" % (params_file, step)) logging.debug("From loaded model : history = %s", history) return State(step=step, params=params, history=history)
[ "def", "restore_state", "(", "output_dir", ")", ":", "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 loaded from %s at step %d\"", "%", "(", "params_file", ",", "step", ")", ")", "logging", ".", "debug", "(", "\"From loaded model : history = %s\"", ",", "history", ")", "return", "State", "(", "step", "=", "step", ",", "params", "=", "params", ",", "history", "=", "history", ")" ]
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".format(state.step)) with gfile.GFile(params_file, "wb") as f: pickle.dump((state.params, state.step, state.history), f) log("Model saved to %s" % params_file, stdout=False)
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".format(state.step)) with gfile.GFile(params_file, "wb") as f: pickle.dump((state.params, state.step, state.history), f) log("Model saved to %s" % params_file, stdout=False)
[ "def", "save_state", "(", "state", ",", "output_dir", ",", "keep", "=", "False", ")", ":", "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\"", ".", "format", "(", "state", ".", "step", ")", ")", "with", "gfile", ".", "GFile", "(", "params_file", ",", "\"wb\"", ")", "as", "f", ":", "pickle", ".", "dump", "(", "(", "state", ".", "params", ",", "state", ".", "step", ",", "state", ".", "history", ")", ",", "f", ")", "log", "(", "\"Model saved to %s\"", "%", "params_file", ",", "stdout", "=", "False", ")" ]
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-comprehension itertools.islice(input_stream(), eval_steps), predict_fun, _METRICS, rng) for input_stream in [inputs.train_eval_stream, inputs.eval_stream]] if train_sw: log_metrics(train_metrics, train_sw, "train", step, history=history) if eval_sw: log_metrics(eval_metrics, eval_sw, "eval", step, history=history) step_log(step, "Finished evaluation") return train_metrics, eval_metrics
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-comprehension itertools.islice(input_stream(), eval_steps), predict_fun, _METRICS, rng) for input_stream in [inputs.train_eval_stream, inputs.eval_stream]] if train_sw: log_metrics(train_metrics, train_sw, "train", step, history=history) if eval_sw: log_metrics(eval_metrics, eval_sw, "eval", step, history=history) step_log(step, "Finished evaluation") return train_metrics, eval_metrics
[ "def", "evaluate_train_and_eval", "(", "step", ",", "inputs", ",", "predict_fun", ",", "eval_steps", ",", "rng", ",", "train_sw", "=", "None", ",", "eval_sw", "=", "None", ",", "history", "=", "None", ")", ":", "step_log", "(", "step", ",", "\"Evaluation\"", ")", "train_metrics", ",", "eval_metrics", "=", "[", "evaluate", "(", "# pylint: disable=g-complex-comprehension", "itertools", ".", "islice", "(", "input_stream", "(", ")", ",", "eval_steps", ")", ",", "predict_fun", ",", "_METRICS", ",", "rng", ")", "for", "input_stream", "in", "[", "inputs", ".", "train_eval_stream", ",", "inputs", ".", "eval_stream", "]", "]", "if", "train_sw", ":", "log_metrics", "(", "train_metrics", ",", "train_sw", ",", "\"train\"", ",", "step", ",", "history", "=", "history", ")", "if", "eval_sw", ":", "log_metrics", "(", "eval_metrics", ",", "eval_sw", ",", "\"eval\"", ",", "step", ",", "history", "=", "history", ")", "step_log", "(", "step", ",", "\"Finished evaluation\"", ")", "return", "train_metrics", ",", "eval_metrics" ]
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)) full_name = "metrics/" + name if history: history.append(log_prefix, full_name, step, value) if summ_writer: summ_writer.scalar(full_name, value, step)
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)) full_name = "metrics/" + name if history: history.append(log_prefix, full_name, step, value) if summ_writer: summ_writer.scalar(full_name, value, step)
[ "def", "log_metrics", "(", "metrics", ",", "summ_writer", ",", "log_prefix", ",", "step", ",", "history", "=", "None", ")", ":", "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", ")", ")", "full_name", "=", "\"metrics/\"", "+", "name", "if", "history", ":", "history", ".", "append", "(", "log_prefix", ",", "full_name", ",", "step", ",", "value", ")", "if", "summ_writer", ":", "summ_writer", ".", "scalar", "(", "full_name", ",", "value", ",", "step", ")" ]
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 = random.randint(0, 2**31 - 1) tf.set_random_seed(seed) numpy.random.seed(seed) return jax_random.get_prng(seed)
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 = random.randint(0, 2**31 - 1) tf.set_random_seed(seed) numpy.random.seed(seed) return jax_random.get_prng(seed)
[ "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", "is", "None", ":", "seed", "=", "random", ".", "randint", "(", "0", ",", "2", "**", "31", "-", "1", ")", "tf", ".", "set_random_seed", "(", "seed", ")", "numpy", ".", "random", ".", "seed", "(", "seed", ")", "return", "jax_random", ".", "get_prng", "(", "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, epoch_steps: int, number of steps in this epoch) """ try: iter(epoch_steps) except TypeError: epoch_steps = itertools.repeat(epoch_steps) step = 0 for epoch, epoch_steps in enumerate(epoch_steps): epoch_steps = min(epoch_steps, steps - step) yield (epoch + 1, epoch_steps) step += epoch_steps if steps and step >= steps: break
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, epoch_steps: int, number of steps in this epoch) """ try: iter(epoch_steps) except TypeError: epoch_steps = itertools.repeat(epoch_steps) step = 0 for epoch, epoch_steps in enumerate(epoch_steps): epoch_steps = min(epoch_steps, steps - step) yield (epoch + 1, epoch_steps) step += epoch_steps if steps and step >= steps: break
[ "def", "epochs", "(", "steps", "=", "None", ",", "epoch_steps", "=", "1", ")", ":", "try", ":", "iter", "(", "epoch_steps", ")", "except", "TypeError", ":", "epoch_steps", "=", "itertools", ".", "repeat", "(", "epoch_steps", ")", "step", "=", "0", "for", "epoch", ",", "epoch_steps", "in", "enumerate", "(", "epoch_steps", ")", ":", "epoch_steps", "=", "min", "(", "epoch_steps", ",", "steps", "-", "step", ")", "yield", "(", "epoch", "+", "1", ",", "epoch_steps", ")", "step", "+=", "epoch_steps", "if", "steps", "and", "step", ">=", "steps", ":", "break" ]
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 epoch)
[ "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) # Multi-devices, pmap and run. @functools.partial(backend.pmap, axis_name="batch") def mapped_predict(x, params, rng): return model_predict(x, params, rng=rng) pred = mapped_predict( reshape_by_device(x, num_devices), params, jax_random.split(rng, num_devices)) # Need to reduce the [device, per-device-batch, ...] tensors back to # a [batch, ...] tensor. The tensors may be nested. if not isinstance(x, (list, tuple)): # Not nested. batch_size = x.shape[0] return np.reshape(pred, [batch_size] + list(pred.shape[2:])) batch_size = x[0].shape[0] return [np.reshape(p, [batch_size] + list(p.shape[2:])) for p in pred] return predict
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) # Multi-devices, pmap and run. @functools.partial(backend.pmap, axis_name="batch") def mapped_predict(x, params, rng): return model_predict(x, params, rng=rng) pred = mapped_predict( reshape_by_device(x, num_devices), params, jax_random.split(rng, num_devices)) # Need to reduce the [device, per-device-batch, ...] tensors back to # a [batch, ...] tensor. The tensors may be nested. if not isinstance(x, (list, tuple)): # Not nested. batch_size = x.shape[0] return np.reshape(pred, [batch_size] + list(pred.shape[2:])) batch_size = x[0].shape[0] return [np.reshape(p, [batch_size] + list(p.shape[2:])) for p in pred] return predict
[ "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 run.", "if", "num_devices", "==", "1", ":", "return", "backend", ".", "jit", "(", "model_predict", ")", "(", "x", ",", "params", ",", "rng", "=", "rng", ")", "# Multi-devices, pmap and run.", "@", "functools", ".", "partial", "(", "backend", ".", "pmap", ",", "axis_name", "=", "\"batch\"", ")", "def", "mapped_predict", "(", "x", ",", "params", ",", "rng", ")", ":", "return", "model_predict", "(", "x", ",", "params", ",", "rng", "=", "rng", ")", "pred", "=", "mapped_predict", "(", "reshape_by_device", "(", "x", ",", "num_devices", ")", ",", "params", ",", "jax_random", ".", "split", "(", "rng", ",", "num_devices", ")", ")", "# Need to reduce the [device, per-device-batch, ...] tensors back to", "# a [batch, ...] tensor. The tensors may be nested.", "if", "not", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "# Not nested.", "batch_size", "=", "x", ".", "shape", "[", "0", "]", "return", "np", ".", "reshape", "(", "pred", ",", "[", "batch_size", "]", "+", "list", "(", "pred", ".", "shape", "[", "2", ":", "]", ")", ")", "batch_size", "=", "x", "[", "0", "]", ".", "shape", "[", "0", "]", "return", "[", "np", ".", "reshape", "(", "p", ",", "[", "batch_size", "]", "+", "list", "(", "p", ".", "shape", "[", "2", ":", "]", ")", ")", "for", "p", "in", "pred", "]", "return", "predict" ]
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(rng[0]) _, opt_update = optimizer(lr_fun) params = trax_opt.get_params(opt_state) return opt_update(i, backend.grad(loss_fun)( params, batch, predict_fun, rng), opt_state), [subrng] return backend.jit(single_update) @functools.partial(backend.pmap, axis_name="batch") def mapped_update(i, opt_state, batch, rng): """This is a multi-device version of the update function above.""" # We assume all tensors have the first dimension = num_devices. rng, subrng = jax_random.split(rng) _, opt_update = optimizer(lr_fun) params = trax_opt.get_params(opt_state) grads = backend.grad(loss_fun)(params, batch, predict_fun, rng) grads = jax.tree_util.tree_map( lambda g: lax.psum(g, "batch"), grads) return opt_update(i, grads, opt_state), subrng def update(i, opt_state, batch, rng): return mapped_update(jax.replicate(i), opt_state, batch, rng) return update
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(rng[0]) _, opt_update = optimizer(lr_fun) params = trax_opt.get_params(opt_state) return opt_update(i, backend.grad(loss_fun)( params, batch, predict_fun, rng), opt_state), [subrng] return backend.jit(single_update) @functools.partial(backend.pmap, axis_name="batch") def mapped_update(i, opt_state, batch, rng): """This is a multi-device version of the update function above.""" # We assume all tensors have the first dimension = num_devices. rng, subrng = jax_random.split(rng) _, opt_update = optimizer(lr_fun) params = trax_opt.get_params(opt_state) grads = backend.grad(loss_fun)(params, batch, predict_fun, rng) grads = jax.tree_util.tree_map( lambda g: lax.psum(g, "batch"), grads) return opt_update(i, grads, opt_state), subrng def update(i, opt_state, batch, rng): return mapped_update(jax.replicate(i), opt_state, batch, rng) return update
[ "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_state", ",", "batch", ",", "rng", ")", ":", "rng", ",", "subrng", "=", "jax_random", ".", "split", "(", "rng", "[", "0", "]", ")", "_", ",", "opt_update", "=", "optimizer", "(", "lr_fun", ")", "params", "=", "trax_opt", ".", "get_params", "(", "opt_state", ")", "return", "opt_update", "(", "i", ",", "backend", ".", "grad", "(", "loss_fun", ")", "(", "params", ",", "batch", ",", "predict_fun", ",", "rng", ")", ",", "opt_state", ")", ",", "[", "subrng", "]", "return", "backend", ".", "jit", "(", "single_update", ")", "@", "functools", ".", "partial", "(", "backend", ".", "pmap", ",", "axis_name", "=", "\"batch\"", ")", "def", "mapped_update", "(", "i", ",", "opt_state", ",", "batch", ",", "rng", ")", ":", "\"\"\"This is a multi-device version of the update function above.\"\"\"", "# We assume all tensors have the first dimension = num_devices.", "rng", ",", "subrng", "=", "jax_random", ".", "split", "(", "rng", ")", "_", ",", "opt_update", "=", "optimizer", "(", "lr_fun", ")", "params", "=", "trax_opt", ".", "get_params", "(", "opt_state", ")", "grads", "=", "backend", ".", "grad", "(", "loss_fun", ")", "(", "params", ",", "batch", ",", "predict_fun", ",", "rng", ")", "grads", "=", "jax", ".", "tree_util", ".", "tree_map", "(", "lambda", "g", ":", "lax", ".", "psum", "(", "g", ",", "\"batch\"", ")", ",", "grads", ")", "return", "opt_update", "(", "i", ",", "grads", ",", "opt_state", ")", ",", "subrng", "def", "update", "(", "i", ",", "opt_state", ",", "batch", ",", "rng", ")", ":", "return", "mapped_update", "(", "jax", ".", "replicate", "(", "i", ")", ",", "opt_state", ",", "batch", ",", "rng", ")", "return", "update" ]
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) == 1: fan_in = fan_out = shape[0] elif len(shape) == 2: fan_in = shape[0] fan_out = shape[1] else: # Assuming convolution kernels (2D, 3D, or more). # kernel shape: (..., input_depth, depth) receptive_field_size = 1. for dim in shape[:-2]: receptive_field_size *= dim fan_in = shape[-2] * receptive_field_size fan_out = shape[-1] * receptive_field_size if isinstance(fan_in, tf.Dimension): fan_in = fan_in.value if isinstance(fan_out, tf.Dimension): fan_out = fan_out.value return fan_in, fan_out
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) == 1: fan_in = fan_out = shape[0] elif len(shape) == 2: fan_in = shape[0] fan_out = shape[1] else: # Assuming convolution kernels (2D, 3D, or more). # kernel shape: (..., input_depth, depth) receptive_field_size = 1. for dim in shape[:-2]: receptive_field_size *= dim fan_in = shape[-2] * receptive_field_size fan_out = shape[-1] * receptive_field_size if isinstance(fan_in, tf.Dimension): fan_in = fan_in.value if isinstance(fan_out, tf.Dimension): fan_out = fan_out.value return fan_in, fan_out
[ "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", "=", "shape", "[", "0", "]", "elif", "len", "(", "shape", ")", "==", "2", ":", "fan_in", "=", "shape", "[", "0", "]", "fan_out", "=", "shape", "[", "1", "]", "else", ":", "# Assuming convolution kernels (2D, 3D, or more).", "# kernel shape: (..., input_depth, depth)", "receptive_field_size", "=", "1.", "for", "dim", "in", "shape", "[", ":", "-", "2", "]", ":", "receptive_field_size", "*=", "dim", "fan_in", "=", "shape", "[", "-", "2", "]", "*", "receptive_field_size", "fan_out", "=", "shape", "[", "-", "1", "]", "*", "receptive_field_size", "if", "isinstance", "(", "fan_in", ",", "tf", ".", "Dimension", ")", ":", "fan_in", "=", "fan_in", ".", "value", "if", "isinstance", "(", "fan_out", ",", "tf", ".", "Dimension", ")", ":", "fan_out", "=", "fan_out", ".", "value", "return", "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 isinstance(identifier, six.string_types): config = {'class_name': str(identifier), 'config': {}} try: return deserialize(config) except ValueError: return value elif callable(identifier): return identifier return value
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 isinstance(identifier, six.string_types): config = {'class_name': str(identifier), 'config': {}} try: return deserialize(config) except ValueError: return value elif callable(identifier): return identifier return value
[ "def", "get", "(", "identifier", ",", "value", "=", "None", ")", ":", "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", "isinstance", "(", "identifier", ",", "six", ".", "string_types", ")", ":", "config", "=", "{", "'class_name'", ":", "str", "(", "identifier", ")", ",", "'config'", ":", "{", "}", "}", "try", ":", "return", "deserialize", "(", "config", ")", "except", "ValueError", ":", "return", "value", "elif", "callable", "(", "identifier", ")", ":", "return", "identifier", "return", "value" ]
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_step.TimeStep) self._time_steps.append(ts)
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_step.TimeStep) self._time_steps.append(ts)
[ "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", ".", "TimeStep", ")", "self", ".", "_time_steps", ".", "append", "(", "ts", ")" ]
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_steps", "[", "-", "1", "]", ".", "replace", "(", "*", "*", "replace_time_step_kwargs", ")" ]
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.processed_reward is not None: processed_rewards += ts.processed_reward return raw_rewards, processed_rewards
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.processed_reward is not None: processed_rewards += ts.processed_reward return raw_rewards, processed_rewards
[ "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", "not", "None", ":", "raw_rewards", "+=", "ts", ".", "raw_reward", "if", "ts", ".", "processed_reward", "is", "not", "None", ":", "processed_rewards", "+=", "ts", ".", "processed_reward", "return", "raw_rewards", ",", "processed_rewards" ]
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.append(trajectory) # Make a new one to replace it. self._trajectories[index] = Trajectory()
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.append(trajectory) # Make a new one to replace it. self._trajectories[index] = Trajectory()
[ "def", "_complete_trajectory", "(", "self", ",", "trajectory", ",", "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", ".", "append", "(", "trajectory", ")", "# Make a new one to replace it.", "self", ".", "_trajectories", "[", "index", "]", "=", "Trajectory", "(", ")" ]
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._completed_trajectories. Args: indices: 1-D np.ndarray stating the indices to reset. observations: np.ndarray of shape (indices len, obs.shape) of observations """ # Pre-conditions: indices, observations are np arrays. # : indices is one-dimensional. # : their first dimension (batch) is the same. assert isinstance(indices, np.ndarray) assert len(indices.shape) == 1 assert isinstance(observations, np.ndarray) assert indices.shape[0] == observations.shape[0] for index, observation in zip(indices, observations): trajectory = self._trajectories[index] # Are we starting a new trajectory at the given index? if not trajectory.is_active: # Then create a new time-step here with the given observation. trajectory.add_time_step(observation=observation) # That's all we need to do here. continue # If however we are resetting a currently active trajectory then we need # to put that in self._completed_trajectories and make a new trajectory # with the current observation. # TODO(afrozm): Should we mark these are done? Or is the done=False and # this being the last time-step in the trajectory good enough to recognize # that this was reset? # Mark trajectory as completed and move into completed_trajectories. self._complete_trajectory(trajectory, index) # Put the observation in the newly created trajectory. # TODO(afrozm): Add 0 reward. self._trajectories[index].add_time_step(observation=observation)
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._completed_trajectories. Args: indices: 1-D np.ndarray stating the indices to reset. observations: np.ndarray of shape (indices len, obs.shape) of observations """ # Pre-conditions: indices, observations are np arrays. # : indices is one-dimensional. # : their first dimension (batch) is the same. assert isinstance(indices, np.ndarray) assert len(indices.shape) == 1 assert isinstance(observations, np.ndarray) assert indices.shape[0] == observations.shape[0] for index, observation in zip(indices, observations): trajectory = self._trajectories[index] # Are we starting a new trajectory at the given index? if not trajectory.is_active: # Then create a new time-step here with the given observation. trajectory.add_time_step(observation=observation) # That's all we need to do here. continue # If however we are resetting a currently active trajectory then we need # to put that in self._completed_trajectories and make a new trajectory # with the current observation. # TODO(afrozm): Should we mark these are done? Or is the done=False and # this being the last time-step in the trajectory good enough to recognize # that this was reset? # Mark trajectory as completed and move into completed_trajectories. self._complete_trajectory(trajectory, index) # Put the observation in the newly created trajectory. # TODO(afrozm): Add 0 reward. self._trajectories[index].add_time_step(observation=observation)
[ "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", ",", "np", ".", "ndarray", ")", "assert", "len", "(", "indices", ".", "shape", ")", "==", "1", "assert", "isinstance", "(", "observations", ",", "np", ".", "ndarray", ")", "assert", "indices", ".", "shape", "[", "0", "]", "==", "observations", ".", "shape", "[", "0", "]", "for", "index", ",", "observation", "in", "zip", "(", "indices", ",", "observations", ")", ":", "trajectory", "=", "self", ".", "_trajectories", "[", "index", "]", "# Are we starting a new trajectory at the given index?", "if", "not", "trajectory", ".", "is_active", ":", "# Then create a new time-step here with the given observation.", "trajectory", ".", "add_time_step", "(", "observation", "=", "observation", ")", "# That's all we need to do here.", "continue", "# If however we are resetting a currently active trajectory then we need", "# to put that in self._completed_trajectories and make a new trajectory", "# with the current observation.", "# TODO(afrozm): Should we mark these are done? Or is the done=False and", "# this being the last time-step in the trajectory good enough to recognize", "# that this was reset?", "# Mark trajectory as completed and move into completed_trajectories.", "self", ".", "_complete_trajectory", "(", "trajectory", ",", "index", ")", "# Put the observation in the newly created trajectory.", "# TODO(afrozm): Add 0 reward.", "self", ".", "_trajectories", "[", "index", "]", ".", "add_time_step", "(", "observation", "=", "observation", ")" ]
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: indices: 1-D np.ndarray stating the indices to reset. observations: np.ndarray of shape (indices len, obs.shape) of observations
[ "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", ".", "_complete_trajectory", "(", "trajectory", ",", "index", ")" ]
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 completed_trajectories. Args: observations: ndarray of first dimension self.batch_size, which has the observations after we've stepped, i.e. s_{t+1} where t is the current state. raw_rewards: ndarray of first dimension self.batch_size containing raw rewards i.e. r_{t+1}. processed_rewards: ndarray of first dimension self.batch_size containing processed rewards. i.e. r_{t+1} dones: ndarray of first dimension self.batch_size, containing true at an index if that env is done, i.e. d_{t+1} actions: ndarray of first dimension self.batch_size, containing actions applied at the current time-step, which leads to the observations rewards and done at the next time-step, i.e. a_t """ # Pre-conditions assert isinstance(observations, np.ndarray) assert isinstance(raw_rewards, np.ndarray) assert isinstance(processed_rewards, np.ndarray) assert isinstance(dones, np.ndarray) assert isinstance(actions, np.ndarray) # We assume that we step in all envs, i.e. not like reset where we can reset # some envs and not others. assert self.batch_size == observations.shape[0] assert self.batch_size == raw_rewards.shape[0] assert self.batch_size == processed_rewards.shape[0] assert self.batch_size == dones.shape[0] assert self.batch_size == actions.shape[0] for index in range(self.batch_size): trajectory = self._trajectories[index] # NOTE: If the trajectory isn't active, that means it doesn't have any # time-steps in it, but we are in step, so the assumption is that it has # a prior observation from which we are stepping away from. # TODO(afrozm): Let's re-visit this if it becomes too restrictive. assert trajectory.is_active # To this trajectory's last time-step, set actions. trajectory.change_last_time_step(action=actions[index]) # Create a new time-step to add observation, done & rewards (no actions). trajectory.add_time_step( observation=observations[index], done=dones[index], raw_reward=raw_rewards[index], processed_reward=processed_rewards[index]) # If the trajectory is completed, i.e. dones[index] == True, then we # account for it right-away. if dones[index]: self._complete_trajectory(trajectory, index) # NOTE: The new trajectory at `index` is going to be in-active and # `reset` should be called on it. assert not self._trajectories[index].is_active
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 completed_trajectories. Args: observations: ndarray of first dimension self.batch_size, which has the observations after we've stepped, i.e. s_{t+1} where t is the current state. raw_rewards: ndarray of first dimension self.batch_size containing raw rewards i.e. r_{t+1}. processed_rewards: ndarray of first dimension self.batch_size containing processed rewards. i.e. r_{t+1} dones: ndarray of first dimension self.batch_size, containing true at an index if that env is done, i.e. d_{t+1} actions: ndarray of first dimension self.batch_size, containing actions applied at the current time-step, which leads to the observations rewards and done at the next time-step, i.e. a_t """ # Pre-conditions assert isinstance(observations, np.ndarray) assert isinstance(raw_rewards, np.ndarray) assert isinstance(processed_rewards, np.ndarray) assert isinstance(dones, np.ndarray) assert isinstance(actions, np.ndarray) # We assume that we step in all envs, i.e. not like reset where we can reset # some envs and not others. assert self.batch_size == observations.shape[0] assert self.batch_size == raw_rewards.shape[0] assert self.batch_size == processed_rewards.shape[0] assert self.batch_size == dones.shape[0] assert self.batch_size == actions.shape[0] for index in range(self.batch_size): trajectory = self._trajectories[index] # NOTE: If the trajectory isn't active, that means it doesn't have any # time-steps in it, but we are in step, so the assumption is that it has # a prior observation from which we are stepping away from. # TODO(afrozm): Let's re-visit this if it becomes too restrictive. assert trajectory.is_active # To this trajectory's last time-step, set actions. trajectory.change_last_time_step(action=actions[index]) # Create a new time-step to add observation, done & rewards (no actions). trajectory.add_time_step( observation=observations[index], done=dones[index], raw_reward=raw_rewards[index], processed_reward=processed_rewards[index]) # If the trajectory is completed, i.e. dones[index] == True, then we # account for it right-away. if dones[index]: self._complete_trajectory(trajectory, index) # NOTE: The new trajectory at `index` is going to be in-active and # `reset` should be called on it. assert not self._trajectories[index].is_active
[ "def", "step", "(", "self", ",", "observations", ",", "raw_rewards", ",", "processed_rewards", ",", "dones", ",", "actions", ")", ":", "# Pre-conditions", "assert", "isinstance", "(", "observations", ",", "np", ".", "ndarray", ")", "assert", "isinstance", "(", "raw_rewards", ",", "np", ".", "ndarray", ")", "assert", "isinstance", "(", "processed_rewards", ",", "np", ".", "ndarray", ")", "assert", "isinstance", "(", "dones", ",", "np", ".", "ndarray", ")", "assert", "isinstance", "(", "actions", ",", "np", ".", "ndarray", ")", "# We assume that we step in all envs, i.e. not like reset where we can reset", "# some envs and not others.", "assert", "self", ".", "batch_size", "==", "observations", ".", "shape", "[", "0", "]", "assert", "self", ".", "batch_size", "==", "raw_rewards", ".", "shape", "[", "0", "]", "assert", "self", ".", "batch_size", "==", "processed_rewards", ".", "shape", "[", "0", "]", "assert", "self", ".", "batch_size", "==", "dones", ".", "shape", "[", "0", "]", "assert", "self", ".", "batch_size", "==", "actions", ".", "shape", "[", "0", "]", "for", "index", "in", "range", "(", "self", ".", "batch_size", ")", ":", "trajectory", "=", "self", ".", "_trajectories", "[", "index", "]", "# NOTE: If the trajectory isn't active, that means it doesn't have any", "# time-steps in it, but we are in step, so the assumption is that it has", "# a prior observation from which we are stepping away from.", "# TODO(afrozm): Let's re-visit this if it becomes too restrictive.", "assert", "trajectory", ".", "is_active", "# To this trajectory's last time-step, set actions.", "trajectory", ".", "change_last_time_step", "(", "action", "=", "actions", "[", "index", "]", ")", "# Create a new time-step to add observation, done & rewards (no actions).", "trajectory", ".", "add_time_step", "(", "observation", "=", "observations", "[", "index", "]", ",", "done", "=", "dones", "[", "index", "]", ",", "raw_reward", "=", "raw_rewards", "[", "index", "]", ",", "processed_reward", "=", "processed_rewards", "[", "index", "]", ")", "# If the trajectory is completed, i.e. dones[index] == True, then we", "# account for it right-away.", "if", "dones", "[", "index", "]", ":", "self", ".", "_complete_trajectory", "(", "trajectory", ",", "index", ")", "# NOTE: The new trajectory at `index` is going to be in-active and", "# `reset` should be called on it.", "assert", "not", "self", ".", "_trajectories", "[", "index", "]", ".", "is_active" ]
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.batch_size, which has the observations after we've stepped, i.e. s_{t+1} where t is the current state. raw_rewards: ndarray of first dimension self.batch_size containing raw rewards i.e. r_{t+1}. processed_rewards: ndarray of first dimension self.batch_size containing processed rewards. i.e. r_{t+1} dones: ndarray of first dimension self.batch_size, containing true at an index if that env is done, i.e. d_{t+1} actions: ndarray of first dimension self.batch_size, containing actions applied at the current time-step, which leads to the observations rewards and done at the next time-step, i.e. a_t
[ "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_observations: (self.batch_size, n * boundary + 1) + OBS time_steps: integer list of length = self.batch_size """ list_observations_np_ts = [t.observations_np for t in self.trajectories] # Every element in `list_observations_np_ts` is shaped (t,) + OBS OBS = list_observations_np_ts[0].shape[1:] # pylint: disable=invalid-name num_time_steps = [t.num_time_steps for t in self.trajectories] t_max = max(num_time_steps) # t_max is rounded to the next multiple of `boundary` boundary = int(boundary) bucket_length = boundary * int(np.ceil(float(t_max) / boundary)) def padding_config(obs): # We're padding the first axis only, since that is the time-step. num_to_pad = bucket_length + 1 - obs.shape[0] return [(0, num_to_pad)] + [(0, 0)] * len(OBS) return np.stack([ np.pad(obs, padding_config(obs), "constant") for obs in list_observations_np_ts]), num_time_steps
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_observations: (self.batch_size, n * boundary + 1) + OBS time_steps: integer list of length = self.batch_size """ list_observations_np_ts = [t.observations_np for t in self.trajectories] # Every element in `list_observations_np_ts` is shaped (t,) + OBS OBS = list_observations_np_ts[0].shape[1:] # pylint: disable=invalid-name num_time_steps = [t.num_time_steps for t in self.trajectories] t_max = max(num_time_steps) # t_max is rounded to the next multiple of `boundary` boundary = int(boundary) bucket_length = boundary * int(np.ceil(float(t_max) / boundary)) def padding_config(obs): # We're padding the first axis only, since that is the time-step. num_to_pad = bucket_length + 1 - obs.shape[0] return [(0, num_to_pad)] + [(0, 0)] * len(OBS) return np.stack([ np.pad(obs, padding_config(obs), "constant") for obs in list_observations_np_ts]), num_time_steps
[ "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", "=", "list_observations_np_ts", "[", "0", "]", ".", "shape", "[", "1", ":", "]", "# pylint: disable=invalid-name", "num_time_steps", "=", "[", "t", ".", "num_time_steps", "for", "t", "in", "self", ".", "trajectories", "]", "t_max", "=", "max", "(", "num_time_steps", ")", "# t_max is rounded to the next multiple of `boundary`", "boundary", "=", "int", "(", "boundary", ")", "bucket_length", "=", "boundary", "*", "int", "(", "np", ".", "ceil", "(", "float", "(", "t_max", ")", "/", "boundary", ")", ")", "def", "padding_config", "(", "obs", ")", ":", "# We're padding the first axis only, since that is the time-step.", "num_to_pad", "=", "bucket_length", "+", "1", "-", "obs", ".", "shape", "[", "0", "]", "return", "[", "(", "0", ",", "num_to_pad", ")", "]", "+", "[", "(", "0", ",", "0", ")", "]", "*", "len", "(", "OBS", ")", "return", "np", ".", "stack", "(", "[", "np", ".", "pad", "(", "obs", ",", "padding_config", "(", "obs", ")", ",", "\"constant\"", ")", "for", "obs", "in", "list_observations_np_ts", "]", ")", ",", "num_time_steps" ]
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) + OBS time_steps: integer list of length = self.batch_size
[ "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 else: file_name = _DEV_SET squad_file = generator_utils.maybe_download(tmp_dir, file_name, os.path.join(_URL, file_name)) with tf.gfile.GFile(squad_file, mode="r") as fp: squad = json.load(fp) version = squad["version"] for article in squad["data"]: if "title" in article: title = article["title"].strip() else: title = "no title" for paragraph in article["paragraphs"]: context = paragraph["context"].strip() for qa in paragraph["qas"]: question = qa["question"].strip() id_ = qa["id"] answer_starts = [answer["answer_start"] for answer in qa["answers"]] answers = [answer["text"].strip() for answer in qa["answers"]] # Features currently used are "context", "question", and "answers". # Others are extracted here for the ease of future expansions. example = { "version": version, "title": title, "context": context, "question": question, "id": id_, "answer_starts": answer_starts, "answers": answers, "num_answers": len(answers), "is_supervised": True, } yield example
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 else: file_name = _DEV_SET squad_file = generator_utils.maybe_download(tmp_dir, file_name, os.path.join(_URL, file_name)) with tf.gfile.GFile(squad_file, mode="r") as fp: squad = json.load(fp) version = squad["version"] for article in squad["data"]: if "title" in article: title = article["title"].strip() else: title = "no title" for paragraph in article["paragraphs"]: context = paragraph["context"].strip() for qa in paragraph["qas"]: question = qa["question"].strip() id_ = qa["id"] answer_starts = [answer["answer_start"] for answer in qa["answers"]] answers = [answer["text"].strip() for answer in qa["answers"]] # Features currently used are "context", "question", and "answers". # Others are extracted here for the ease of future expansions. example = { "version": version, "title": title, "context": context, "question": question, "id": id_, "answer_starts": answer_starts, "answers": answers, "num_answers": len(answers), "is_supervised": True, } yield example
[ "def", "_generate_examples", "(", "tmp_dir", ",", "dataset_split", ")", ":", "if", "dataset_split", "==", "problem", ".", "DatasetSplit", ".", "TRAIN", ":", "file_name", "=", "_TRAINING_SET", "else", ":", "file_name", "=", "_DEV_SET", "squad_file", "=", "generator_utils", ".", "maybe_download", "(", "tmp_dir", ",", "file_name", ",", "os", ".", "path", ".", "join", "(", "_URL", ",", "file_name", ")", ")", "with", "tf", ".", "gfile", ".", "GFile", "(", "squad_file", ",", "mode", "=", "\"r\"", ")", "as", "fp", ":", "squad", "=", "json", ".", "load", "(", "fp", ")", "version", "=", "squad", "[", "\"version\"", "]", "for", "article", "in", "squad", "[", "\"data\"", "]", ":", "if", "\"title\"", "in", "article", ":", "title", "=", "article", "[", "\"title\"", "]", ".", "strip", "(", ")", "else", ":", "title", "=", "\"no title\"", "for", "paragraph", "in", "article", "[", "\"paragraphs\"", "]", ":", "context", "=", "paragraph", "[", "\"context\"", "]", ".", "strip", "(", ")", "for", "qa", "in", "paragraph", "[", "\"qas\"", "]", ":", "question", "=", "qa", "[", "\"question\"", "]", ".", "strip", "(", ")", "id_", "=", "qa", "[", "\"id\"", "]", "answer_starts", "=", "[", "answer", "[", "\"answer_start\"", "]", "for", "answer", "in", "qa", "[", "\"answers\"", "]", "]", "answers", "=", "[", "answer", "[", "\"text\"", "]", ".", "strip", "(", ")", "for", "answer", "in", "qa", "[", "\"answers\"", "]", "]", "# Features currently used are \"context\", \"question\", and \"answers\".", "# Others are extracted here for the ease of future expansions.", "example", "=", "{", "\"version\"", ":", "version", ",", "\"title\"", ":", "title", ",", "\"context\"", ":", "context", ",", "\"question\"", ":", "question", ",", "\"id\"", ":", "id_", ",", "\"answer_starts\"", ":", "answer_starts", ",", "\"answers\"", ":", "answers", ",", "\"num_answers\"", ":", "len", "(", "answers", ")", ",", "\"is_supervised\"", ":", "True", ",", "}", "yield", "example" ]
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_epsilon=hparams.norm_epsilon)
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_epsilon=hparams.norm_epsilon)
[ "def", "layer_stack_from_hparams", "(", "hparams", ",", "prefix", ")", ":", "layers", "=", "hparams", ".", "get", "(", "prefix", "+", "\"layers\"", ")", "return", "transformer", ".", "LayerStack", "(", "[", "layers_registry", "[", "l", "]", "(", "hparams", ",", "prefix", ")", "for", "l", "in", "layers", "]", ",", "dropout_rate", "=", "hparams", ".", "layer_prepostprocess_dropout", ",", "norm_epsilon", "=", "hparams", ".", "norm_epsilon", ")" ]
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 hparams.add_hparam("num_heads", 8) # default of 0 for standard transformer behavior # 1 means a single set of keys and values that are read by all query heads hparams.add_hparam("num_memory_heads", 0) # share attention keys and values hparams.add_hparam("shared_kv", False) # if nonzero then use local attention hparams.add_hparam("local_attention_radius", 128) return hparams
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 hparams.add_hparam("num_heads", 8) # default of 0 for standard transformer behavior # 1 means a single set of keys and values that are read by all query heads hparams.add_hparam("num_memory_heads", 0) # share attention keys and values hparams.add_hparam("shared_kv", False) # if nonzero then use local attention hparams.add_hparam("local_attention_radius", 128) return hparams
[ "def", "mtf_unitransformer_base", "(", ")", ":", "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", "hparams", ".", "add_hparam", "(", "\"num_heads\"", ",", "8", ")", "# default of 0 for standard transformer behavior", "# 1 means a single set of keys and values that are read by all query heads", "hparams", ".", "add_hparam", "(", "\"num_memory_heads\"", ",", "0", ")", "# share attention keys and values", "hparams", ".", "add_hparam", "(", "\"shared_kv\"", ",", "False", ")", "# if nonzero then use local attention", "hparams", ".", "add_hparam", "(", "\"local_attention_radius\"", ",", "128", ")", "return", "hparams" ]
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", ["self_att", "enc_att", "drd"] * 6) hparams.add_hparam("encoder_num_layers", 6) hparams.add_hparam("decoder_num_layers", 6) # number of heads in multihead attention hparams.add_hparam("encoder_num_heads", 8) hparams.add_hparam("decoder_num_heads", 8) hparams.add_hparam("local_attention_radius", 128) # default of 0 for standard transformer behavior # 1 means a single set of keys and values that are read by all query heads hparams.add_hparam("encoder_num_memory_heads", 0) hparams.add_hparam("decoder_num_memory_heads", 0) # share attention keys and values hparams.add_hparam("encoder_shared_kv", False) hparams.add_hparam("decoder_shared_kv", False) # Parameters for computing the maximum decode length in beam search. # Maximum decode length is: # min(max_length, # decode_length_multiplier * input_length + decode_length_constant) hparams.add_hparam("decode_length_multiplier", 1.5) hparams.add_hparam("decode_length_constant", 10.0) # used during decoding hparams.add_hparam("alpha", 0.6) hparams.sampling_temp = 0.0 return hparams
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", ["self_att", "enc_att", "drd"] * 6) hparams.add_hparam("encoder_num_layers", 6) hparams.add_hparam("decoder_num_layers", 6) # number of heads in multihead attention hparams.add_hparam("encoder_num_heads", 8) hparams.add_hparam("decoder_num_heads", 8) hparams.add_hparam("local_attention_radius", 128) # default of 0 for standard transformer behavior # 1 means a single set of keys and values that are read by all query heads hparams.add_hparam("encoder_num_memory_heads", 0) hparams.add_hparam("decoder_num_memory_heads", 0) # share attention keys and values hparams.add_hparam("encoder_shared_kv", False) hparams.add_hparam("decoder_shared_kv", False) # Parameters for computing the maximum decode length in beam search. # Maximum decode length is: # min(max_length, # decode_length_multiplier * input_length + decode_length_constant) hparams.add_hparam("decode_length_multiplier", 1.5) hparams.add_hparam("decode_length_constant", 10.0) # used during decoding hparams.add_hparam("alpha", 0.6) hparams.sampling_temp = 0.0 return hparams
[ "def", "mtf_bitransformer_base", "(", ")", ":", "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\"", ",", "[", "\"self_att\"", ",", "\"enc_att\"", ",", "\"drd\"", "]", "*", "6", ")", "hparams", ".", "add_hparam", "(", "\"encoder_num_layers\"", ",", "6", ")", "hparams", ".", "add_hparam", "(", "\"decoder_num_layers\"", ",", "6", ")", "# number of heads in multihead attention", "hparams", ".", "add_hparam", "(", "\"encoder_num_heads\"", ",", "8", ")", "hparams", ".", "add_hparam", "(", "\"decoder_num_heads\"", ",", "8", ")", "hparams", ".", "add_hparam", "(", "\"local_attention_radius\"", ",", "128", ")", "# default of 0 for standard transformer behavior", "# 1 means a single set of keys and values that are read by all query heads", "hparams", ".", "add_hparam", "(", "\"encoder_num_memory_heads\"", ",", "0", ")", "hparams", ".", "add_hparam", "(", "\"decoder_num_memory_heads\"", ",", "0", ")", "# share attention keys and values", "hparams", ".", "add_hparam", "(", "\"encoder_shared_kv\"", ",", "False", ")", "hparams", ".", "add_hparam", "(", "\"decoder_shared_kv\"", ",", "False", ")", "# Parameters for computing the maximum decode length in beam search.", "# Maximum decode length is:", "# min(max_length,", "# decode_length_multiplier * input_length + decode_length_constant)", "hparams", ".", "add_hparam", "(", "\"decode_length_multiplier\"", ",", "1.5", ")", "hparams", ".", "add_hparam", "(", "\"decode_length_constant\"", ",", "10.0", ")", "# used during decoding", "hparams", ".", "add_hparam", "(", "\"alpha\"", ",", "0.6", ")", "hparams", ".", "sampling_temp", "=", "0.0", "return", "hparams" ]
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_heads = 4 hparams.d_ff = 512 return hparams
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_heads = 4 hparams.d_ff = 512 return hparams
[ "def", "mtf_bitransformer_tiny", "(", ")", ":", "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_heads", "=", "4", "hparams", ".", "d_ff", "=", "512", "return", "hparams" ]
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", "local_self_att", "local_self_att", "moe_2d"] * 4)[:-1] hparams.d_kv = 128 hparams.moe_expert_x = 8 hparams.moe_expert_y = 4 hparams.moe_hidden_size = 32768 hparams.d_ff = 2048 hparams.num_memory_heads = 0 hparams.mesh_shape = "b0:4;b1:8" hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.outer_batch_size = 4 return hparams
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", "local_self_att", "local_self_att", "moe_2d"] * 4)[:-1] hparams.d_kv = 128 hparams.moe_expert_x = 8 hparams.moe_expert_y = 4 hparams.moe_hidden_size = 32768 hparams.d_ff = 2048 hparams.num_memory_heads = 0 hparams.mesh_shape = "b0:4;b1:8" hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.outer_batch_size = 4 return hparams
[ "def", "mtr_lm_v1", "(", ")", ":", "hparams", "=", "mtr_lm_dense", "(", "0", ")", "hparams", ".", "layers", "=", "(", "[", "\"local_self_att\"", ",", "\"local_self_att\"", ",", "\"drd\"", ",", "\"self_att\"", ",", "\"drd\"", ",", "\"local_self_att\"", ",", "\"local_self_att\"", ",", "\"moe_2d\"", "]", "*", "4", ")", "[", ":", "-", "1", "]", "hparams", ".", "d_kv", "=", "128", "hparams", ".", "moe_expert_x", "=", "8", "hparams", ".", "moe_expert_y", "=", "4", "hparams", ".", "moe_hidden_size", "=", "32768", "hparams", ".", "d_ff", "=", "2048", "hparams", ".", "num_memory_heads", "=", "0", "hparams", ".", "mesh_shape", "=", "\"b0:4;b1:8\"", "hparams", ".", "layout", "=", "\"outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0\"", "hparams", ".", "outer_batch_size", "=", "4", "return", "hparams" ]
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() hparams.d_model = 1024 hparams.max_length = 256 hparams.batch_size = 128 hparams.d_ff = int(4096 * n) hparams.d_kv = 128 hparams.encoder_num_heads = int(8 * n) hparams.decoder_num_heads = int(8 * n) # one epoch for translate_enfr_wmt32k_packed = 51400 steps hparams.learning_rate_decay_steps = 51400 hparams.layout = "batch:batch;vocab:model;d_ff:model;heads:model" hparams.mesh_shape = "batch:32" hparams.label_smoothing = 0.1 hparams.layer_prepostprocess_dropout = 0.1 hparams.attention_dropout = 0.1 hparams.relu_dropout = 0.1 return hparams
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() hparams.d_model = 1024 hparams.max_length = 256 hparams.batch_size = 128 hparams.d_ff = int(4096 * n) hparams.d_kv = 128 hparams.encoder_num_heads = int(8 * n) hparams.decoder_num_heads = int(8 * n) # one epoch for translate_enfr_wmt32k_packed = 51400 steps hparams.learning_rate_decay_steps = 51400 hparams.layout = "batch:batch;vocab:model;d_ff:model;heads:model" hparams.mesh_shape = "batch:32" hparams.label_smoothing = 0.1 hparams.layer_prepostprocess_dropout = 0.1 hparams.attention_dropout = 0.1 hparams.relu_dropout = 0.1 return hparams
[ "def", "mtr_tr_dense", "(", "sz", ")", ":", "n", "=", "2", "**", "sz", "hparams", "=", "mtf_bitransformer_base", "(", ")", "hparams", ".", "d_model", "=", "1024", "hparams", ".", "max_length", "=", "256", "hparams", ".", "batch_size", "=", "128", "hparams", ".", "d_ff", "=", "int", "(", "4096", "*", "n", ")", "hparams", ".", "d_kv", "=", "128", "hparams", ".", "encoder_num_heads", "=", "int", "(", "8", "*", "n", ")", "hparams", ".", "decoder_num_heads", "=", "int", "(", "8", "*", "n", ")", "# one epoch for translate_enfr_wmt32k_packed = 51400 steps", "hparams", ".", "learning_rate_decay_steps", "=", "51400", "hparams", ".", "layout", "=", "\"batch:batch;vocab:model;d_ff:model;heads:model\"", "hparams", ".", "mesh_shape", "=", "\"batch:32\"", "hparams", ".", "label_smoothing", "=", "0.1", "hparams", ".", "layer_prepostprocess_dropout", "=", "0.1", "hparams", ".", "attention_dropout", "=", "0.1", "hparams", ".", "relu_dropout", "=", "0.1", "return", "hparams" ]
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", "=", "32", "return", "hparams" ]
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_dropout_broadcast_dims = ( common_layers.comma_separated_string_to_integer_list( getattr(hparams, "attention_dropout_broadcast_dims", ""))) with tf.variable_scope(name): ffn_unit = functools.partial( # use encoder ffn, since decoder ffn use left padding universal_transformer_util.transformer_encoder_ffn_unit, hparams=hparams, nonpadding_mask=nonpadding) attention_unit = functools.partial( universal_transformer_util.transformer_decoder_attention_unit, hparams=hparams, encoder_output=encoder_output, decoder_self_attention_bias=decoder_self_attention_bias, encoder_decoder_attention_bias=encoder_decoder_attention_bias, attention_dropout_broadcast_dims=attention_dropout_broadcast_dims, save_weights_to=save_weights_to, make_image_summary=make_image_summary) x, extra_output = universal_transformer_util.universal_transformer_layer( x, hparams, ffn_unit, attention_unit) return common_layers.layer_preprocess(x, hparams), extra_output
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_dropout_broadcast_dims = ( common_layers.comma_separated_string_to_integer_list( getattr(hparams, "attention_dropout_broadcast_dims", ""))) with tf.variable_scope(name): ffn_unit = functools.partial( # use encoder ffn, since decoder ffn use left padding universal_transformer_util.transformer_encoder_ffn_unit, hparams=hparams, nonpadding_mask=nonpadding) attention_unit = functools.partial( universal_transformer_util.transformer_decoder_attention_unit, hparams=hparams, encoder_output=encoder_output, decoder_self_attention_bias=decoder_self_attention_bias, encoder_decoder_attention_bias=encoder_decoder_attention_bias, attention_dropout_broadcast_dims=attention_dropout_broadcast_dims, save_weights_to=save_weights_to, make_image_summary=make_image_summary) x, extra_output = universal_transformer_util.universal_transformer_layer( x, hparams, ffn_unit, attention_unit) return common_layers.layer_preprocess(x, hparams), extra_output
[ "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", ")", ":", "x", "=", "decoder_input", "attention_dropout_broadcast_dims", "=", "(", "common_layers", ".", "comma_separated_string_to_integer_list", "(", "getattr", "(", "hparams", ",", "\"attention_dropout_broadcast_dims\"", ",", "\"\"", ")", ")", ")", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "ffn_unit", "=", "functools", ".", "partial", "(", "# use encoder ffn, since decoder ffn use left padding", "universal_transformer_util", ".", "transformer_encoder_ffn_unit", ",", "hparams", "=", "hparams", ",", "nonpadding_mask", "=", "nonpadding", ")", "attention_unit", "=", "functools", ".", "partial", "(", "universal_transformer_util", ".", "transformer_decoder_attention_unit", ",", "hparams", "=", "hparams", ",", "encoder_output", "=", "encoder_output", ",", "decoder_self_attention_bias", "=", "decoder_self_attention_bias", ",", "encoder_decoder_attention_bias", "=", "encoder_decoder_attention_bias", ",", "attention_dropout_broadcast_dims", "=", "attention_dropout_broadcast_dims", ",", "save_weights_to", "=", "save_weights_to", ",", "make_image_summary", "=", "make_image_summary", ")", "x", ",", "extra_output", "=", "universal_transformer_util", ".", "universal_transformer_layer", "(", "x", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ")", "return", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "extra_output" ]
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", ",", "init_zero", "=", "(", "not", "relu", ")", ")", "if", "relu", ":", "inputs", "=", "mtf", ".", "relu", "(", "inputs", ")", "return", "inputs" ]
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, 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()) hparams: hyperparameters for model name: a string nonpadding: optional Tensor with shape [batch_size, encoder_length] indicating what positions are not padding. This must either be passed in, which we do for "packed" datasets, or inferred from encoder_self_attention_bias. The knowledge about padding is used for pad_remover(efficiency) and to mask out padding in convoltutional layers. save_weights_to: an optional dictionary to capture attention weights for vizualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: y: a Tensors as the output of the encoder extra_output: which can be used to pass extra information to the body """ x = encoder_input attention_dropout_broadcast_dims = ( common_layers.comma_separated_string_to_integer_list( getattr(hparams, "attention_dropout_broadcast_dims", ""))) with tf.variable_scope(name): if nonpadding is not None: padding = 1.0 - nonpadding else: padding = common_attention.attention_bias_to_padding( encoder_self_attention_bias) nonpadding = 1.0 - padding pad_remover = None if hparams.use_pad_remover and not common_layers.is_xla_compiled(): pad_remover = expert_utils.PadRemover(padding) ffn_unit = functools.partial( transformer_encoder_ffn_unit, hparams=hparams, nonpadding_mask=nonpadding, pad_remover=pad_remover) attention_unit = functools.partial( transformer_encoder_attention_unit, hparams=hparams, encoder_self_attention_bias=encoder_self_attention_bias, attention_dropout_broadcast_dims=attention_dropout_broadcast_dims, save_weights_to=save_weights_to, make_image_summary=make_image_summary) x, extra_output = universal_transformer_layer( x, hparams, ffn_unit, attention_unit, pad_remover=pad_remover) return common_layers.layer_preprocess(x, hparams), extra_output
python
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()) hparams: hyperparameters for model name: a string nonpadding: optional Tensor with shape [batch_size, encoder_length] indicating what positions are not padding. This must either be passed in, which we do for "packed" datasets, or inferred from encoder_self_attention_bias. The knowledge about padding is used for pad_remover(efficiency) and to mask out padding in convoltutional layers. save_weights_to: an optional dictionary to capture attention weights for vizualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: y: a Tensors as the output of the encoder extra_output: which can be used to pass extra information to the body """ x = encoder_input attention_dropout_broadcast_dims = ( common_layers.comma_separated_string_to_integer_list( getattr(hparams, "attention_dropout_broadcast_dims", ""))) with tf.variable_scope(name): if nonpadding is not None: padding = 1.0 - nonpadding else: padding = common_attention.attention_bias_to_padding( encoder_self_attention_bias) nonpadding = 1.0 - padding pad_remover = None if hparams.use_pad_remover and not common_layers.is_xla_compiled(): pad_remover = expert_utils.PadRemover(padding) ffn_unit = functools.partial( transformer_encoder_ffn_unit, hparams=hparams, nonpadding_mask=nonpadding, pad_remover=pad_remover) attention_unit = functools.partial( transformer_encoder_attention_unit, hparams=hparams, encoder_self_attention_bias=encoder_self_attention_bias, attention_dropout_broadcast_dims=attention_dropout_broadcast_dims, save_weights_to=save_weights_to, make_image_summary=make_image_summary) x, extra_output = universal_transformer_layer( x, hparams, ffn_unit, attention_unit, pad_remover=pad_remover) return common_layers.layer_preprocess(x, hparams), extra_output
[ "def", "universal_transformer_encoder", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "hparams", ",", "name", "=", "\"encoder\"", ",", "nonpadding", "=", "None", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ")", ":", "x", "=", "encoder_input", "attention_dropout_broadcast_dims", "=", "(", "common_layers", ".", "comma_separated_string_to_integer_list", "(", "getattr", "(", "hparams", ",", "\"attention_dropout_broadcast_dims\"", ",", "\"\"", ")", ")", ")", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "if", "nonpadding", "is", "not", "None", ":", "padding", "=", "1.0", "-", "nonpadding", "else", ":", "padding", "=", "common_attention", ".", "attention_bias_to_padding", "(", "encoder_self_attention_bias", ")", "nonpadding", "=", "1.0", "-", "padding", "pad_remover", "=", "None", "if", "hparams", ".", "use_pad_remover", "and", "not", "common_layers", ".", "is_xla_compiled", "(", ")", ":", "pad_remover", "=", "expert_utils", ".", "PadRemover", "(", "padding", ")", "ffn_unit", "=", "functools", ".", "partial", "(", "transformer_encoder_ffn_unit", ",", "hparams", "=", "hparams", ",", "nonpadding_mask", "=", "nonpadding", ",", "pad_remover", "=", "pad_remover", ")", "attention_unit", "=", "functools", ".", "partial", "(", "transformer_encoder_attention_unit", ",", "hparams", "=", "hparams", ",", "encoder_self_attention_bias", "=", "encoder_self_attention_bias", ",", "attention_dropout_broadcast_dims", "=", "attention_dropout_broadcast_dims", ",", "save_weights_to", "=", "save_weights_to", ",", "make_image_summary", "=", "make_image_summary", ")", "x", ",", "extra_output", "=", "universal_transformer_layer", "(", "x", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "pad_remover", ")", "return", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "extra_output" ]
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()) hparams: hyperparameters for model name: a string nonpadding: optional Tensor with shape [batch_size, encoder_length] indicating what positions are not padding. This must either be passed in, which we do for "packed" datasets, or inferred from encoder_self_attention_bias. The knowledge about padding is used for pad_remover(efficiency) and to mask out padding in convoltutional layers. save_weights_to: an optional dictionary to capture attention weights for vizualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: y: a Tensors as the output of the encoder extra_output: which can be used to pass extra information to the body
[ "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 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 be memory, ponder time, etc.) Raises: ValueError: Unknown recurrence type """ def add_vanilla_transformer_layer(x, num_layers, name): """Passes the input through num_layers of vanilla transformer layers. Args: x: input num_layers: number of layers name: string, prefix of layer names Returns: output of vanilla_transformer_layer """ if hparams.add_position_timing_signal: # In case of add_position_timing_signal=true, we set hparams.pos=None # and add position timing signal at the beginning of each step, so for # the vanilla transformer, we need to add timing signal here. x = common_attention.add_timing_signal_1d(x) for layer in range(num_layers): with tf.variable_scope(name + "layer_%d" % layer): x = ffn_unit(attention_unit(x)) return x with tf.variable_scope("universal_transformer_%s" % hparams.recurrence_type): if (hparams.mix_with_transformer and "before_ut" in hparams.mix_with_transformer): x = add_vanilla_transformer_layer(x, hparams.num_mixedin_layers, "before_ut_") if hparams.recurrence_type == "act": output, extra_output = universal_transformer_act( x, hparams, ffn_unit, attention_unit) else: # for all the other recurrency types with fixed number of steps ut_function, initializer = get_ut_layer(x, hparams, ffn_unit, attention_unit, pad_remover) output, _, extra_output = tf.foldl( ut_function, tf.range(hparams.num_rec_steps), initializer=initializer) # Right now, this is only possible when the transition function is an lstm if (hparams.recurrence_type == "lstm" and hparams.get("use_memory_as_final_state", False)): output = extra_output if (hparams.mix_with_transformer and "after_ut" in hparams.mix_with_transformer): output = add_vanilla_transformer_layer(output, hparams.num_mixedin_layers, "after_ut_") return output, extra_output
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 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 be memory, ponder time, etc.) Raises: ValueError: Unknown recurrence type """ def add_vanilla_transformer_layer(x, num_layers, name): """Passes the input through num_layers of vanilla transformer layers. Args: x: input num_layers: number of layers name: string, prefix of layer names Returns: output of vanilla_transformer_layer """ if hparams.add_position_timing_signal: # In case of add_position_timing_signal=true, we set hparams.pos=None # and add position timing signal at the beginning of each step, so for # the vanilla transformer, we need to add timing signal here. x = common_attention.add_timing_signal_1d(x) for layer in range(num_layers): with tf.variable_scope(name + "layer_%d" % layer): x = ffn_unit(attention_unit(x)) return x with tf.variable_scope("universal_transformer_%s" % hparams.recurrence_type): if (hparams.mix_with_transformer and "before_ut" in hparams.mix_with_transformer): x = add_vanilla_transformer_layer(x, hparams.num_mixedin_layers, "before_ut_") if hparams.recurrence_type == "act": output, extra_output = universal_transformer_act( x, hparams, ffn_unit, attention_unit) else: # for all the other recurrency types with fixed number of steps ut_function, initializer = get_ut_layer(x, hparams, ffn_unit, attention_unit, pad_remover) output, _, extra_output = tf.foldl( ut_function, tf.range(hparams.num_rec_steps), initializer=initializer) # Right now, this is only possible when the transition function is an lstm if (hparams.recurrence_type == "lstm" and hparams.get("use_memory_as_final_state", False)): output = extra_output if (hparams.mix_with_transformer and "after_ut" in hparams.mix_with_transformer): output = add_vanilla_transformer_layer(output, hparams.num_mixedin_layers, "after_ut_") return output, extra_output
[ "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 through num_layers of vanilla transformer layers.\n\n Args:\n x: input\n num_layers: number of layers\n name: string, prefix of layer names\n\n Returns:\n output of vanilla_transformer_layer\n \"\"\"", "if", "hparams", ".", "add_position_timing_signal", ":", "# In case of add_position_timing_signal=true, we set hparams.pos=None", "# and add position timing signal at the beginning of each step, so for", "# the vanilla transformer, we need to add timing signal here.", "x", "=", "common_attention", ".", "add_timing_signal_1d", "(", "x", ")", "for", "layer", "in", "range", "(", "num_layers", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", "+", "\"layer_%d\"", "%", "layer", ")", ":", "x", "=", "ffn_unit", "(", "attention_unit", "(", "x", ")", ")", "return", "x", "with", "tf", ".", "variable_scope", "(", "\"universal_transformer_%s\"", "%", "hparams", ".", "recurrence_type", ")", ":", "if", "(", "hparams", ".", "mix_with_transformer", "and", "\"before_ut\"", "in", "hparams", ".", "mix_with_transformer", ")", ":", "x", "=", "add_vanilla_transformer_layer", "(", "x", ",", "hparams", ".", "num_mixedin_layers", ",", "\"before_ut_\"", ")", "if", "hparams", ".", "recurrence_type", "==", "\"act\"", ":", "output", ",", "extra_output", "=", "universal_transformer_act", "(", "x", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ")", "else", ":", "# for all the other recurrency types with fixed number of steps", "ut_function", ",", "initializer", "=", "get_ut_layer", "(", "x", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", ")", "output", ",", "_", ",", "extra_output", "=", "tf", ".", "foldl", "(", "ut_function", ",", "tf", ".", "range", "(", "hparams", ".", "num_rec_steps", ")", ",", "initializer", "=", "initializer", ")", "# Right now, this is only possible when the transition function is an lstm", "if", "(", "hparams", ".", "recurrence_type", "==", "\"lstm\"", "and", "hparams", ".", "get", "(", "\"use_memory_as_final_state\"", ",", "False", ")", ")", ":", "output", "=", "extra_output", "if", "(", "hparams", ".", "mix_with_transformer", "and", "\"after_ut\"", "in", "hparams", ".", "mix_with_transformer", ")", ":", "output", "=", "add_vanilla_transformer_layer", "(", "output", ",", "hparams", ".", "num_mixedin_layers", ",", "\"after_ut_\"", ")", "return", "output", ",", "extra_output" ]
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 be memory, ponder time, etc.) Raises: ValueError: Unknown recurrence type
[ "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_unit: multi-head attention unit pad_remover: to mask out padding in convolutional layers (efficiency). Returns: ut_function and the ut_initializer Raises: ValueError: Unknown recurrence type """ if hparams.recurrence_type == "basic": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_basic, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit) elif hparams.recurrence_type == "highway": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_highway, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) elif hparams.recurrence_type == "skip": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_skip, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) elif hparams.recurrence_type == "dwa": # memory contains the original input + all the states memory_size = hparams.num_rec_steps + 1 # prepare initializer: memory_empty = tf.zeros([memory_size] + common_layers.shape_list(x)) # filling the first slot with the original input memory = fill_memory_slot(memory_empty, x, 0) ut_initializer = (x, x, memory) # (state, input, memory) ut_function = functools.partial( universal_transformer_depthwise_attention, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit) elif hparams.recurrence_type == "gru": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_with_gru_as_transition_function, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) elif hparams.recurrence_type == "lstm": memory = tf.zeros(common_layers.shape_list(x)) ut_initializer = (x, x, memory) # (state, input, memory) ut_function = functools.partial( universal_transformer_with_lstm_as_transition_function, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) else: raise ValueError("Unknown recurrence type: %s" % hparams.recurrence_type) return ut_function, ut_initializer
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_unit: multi-head attention unit pad_remover: to mask out padding in convolutional layers (efficiency). Returns: ut_function and the ut_initializer Raises: ValueError: Unknown recurrence type """ if hparams.recurrence_type == "basic": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_basic, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit) elif hparams.recurrence_type == "highway": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_highway, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) elif hparams.recurrence_type == "skip": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_skip, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) elif hparams.recurrence_type == "dwa": # memory contains the original input + all the states memory_size = hparams.num_rec_steps + 1 # prepare initializer: memory_empty = tf.zeros([memory_size] + common_layers.shape_list(x)) # filling the first slot with the original input memory = fill_memory_slot(memory_empty, x, 0) ut_initializer = (x, x, memory) # (state, input, memory) ut_function = functools.partial( universal_transformer_depthwise_attention, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit) elif hparams.recurrence_type == "gru": ut_initializer = (x, x, x) # (state, input, memory) ut_function = functools.partial( universal_transformer_with_gru_as_transition_function, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) elif hparams.recurrence_type == "lstm": memory = tf.zeros(common_layers.shape_list(x)) ut_initializer = (x, x, memory) # (state, input, memory) ut_function = functools.partial( universal_transformer_with_lstm_as_transition_function, hparams=hparams, ffn_unit=ffn_unit, attention_unit=attention_unit, pad_remover=pad_remover) else: raise ValueError("Unknown recurrence type: %s" % hparams.recurrence_type) return ut_function, ut_initializer
[ "def", "get_ut_layer", "(", "x", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "if", "hparams", ".", "recurrence_type", "==", "\"basic\"", ":", "ut_initializer", "=", "(", "x", ",", "x", ",", "x", ")", "# (state, input, memory)", "ut_function", "=", "functools", ".", "partial", "(", "universal_transformer_basic", ",", "hparams", "=", "hparams", ",", "ffn_unit", "=", "ffn_unit", ",", "attention_unit", "=", "attention_unit", ")", "elif", "hparams", ".", "recurrence_type", "==", "\"highway\"", ":", "ut_initializer", "=", "(", "x", ",", "x", ",", "x", ")", "# (state, input, memory)", "ut_function", "=", "functools", ".", "partial", "(", "universal_transformer_highway", ",", "hparams", "=", "hparams", ",", "ffn_unit", "=", "ffn_unit", ",", "attention_unit", "=", "attention_unit", ",", "pad_remover", "=", "pad_remover", ")", "elif", "hparams", ".", "recurrence_type", "==", "\"skip\"", ":", "ut_initializer", "=", "(", "x", ",", "x", ",", "x", ")", "# (state, input, memory)", "ut_function", "=", "functools", ".", "partial", "(", "universal_transformer_skip", ",", "hparams", "=", "hparams", ",", "ffn_unit", "=", "ffn_unit", ",", "attention_unit", "=", "attention_unit", ",", "pad_remover", "=", "pad_remover", ")", "elif", "hparams", ".", "recurrence_type", "==", "\"dwa\"", ":", "# memory contains the original input + all the states", "memory_size", "=", "hparams", ".", "num_rec_steps", "+", "1", "# prepare initializer:", "memory_empty", "=", "tf", ".", "zeros", "(", "[", "memory_size", "]", "+", "common_layers", ".", "shape_list", "(", "x", ")", ")", "# filling the first slot with the original input", "memory", "=", "fill_memory_slot", "(", "memory_empty", ",", "x", ",", "0", ")", "ut_initializer", "=", "(", "x", ",", "x", ",", "memory", ")", "# (state, input, memory)", "ut_function", "=", "functools", ".", "partial", "(", "universal_transformer_depthwise_attention", ",", "hparams", "=", "hparams", ",", "ffn_unit", "=", "ffn_unit", ",", "attention_unit", "=", "attention_unit", ")", "elif", "hparams", ".", "recurrence_type", "==", "\"gru\"", ":", "ut_initializer", "=", "(", "x", ",", "x", ",", "x", ")", "# (state, input, memory)", "ut_function", "=", "functools", ".", "partial", "(", "universal_transformer_with_gru_as_transition_function", ",", "hparams", "=", "hparams", ",", "ffn_unit", "=", "ffn_unit", ",", "attention_unit", "=", "attention_unit", ",", "pad_remover", "=", "pad_remover", ")", "elif", "hparams", ".", "recurrence_type", "==", "\"lstm\"", ":", "memory", "=", "tf", ".", "zeros", "(", "common_layers", ".", "shape_list", "(", "x", ")", ")", "ut_initializer", "=", "(", "x", ",", "x", ",", "memory", ")", "# (state, input, memory)", "ut_function", "=", "functools", ".", "partial", "(", "universal_transformer_with_lstm_as_transition_function", ",", "hparams", "=", "hparams", ",", "ffn_unit", "=", "ffn_unit", ",", "attention_unit", "=", "attention_unit", ",", "pad_remover", "=", "pad_remover", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown recurrence type: %s\"", "%", "hparams", ".", "recurrence_type", ")", "return", "ut_function", ",", "ut_initializer" ]
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_initializer Raises: ValueError: Unknown recurrence type
[ "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 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 generally only need this mask for "packed" datasets, because for ordinary datasets, no padding is ever followed by nonpadding. pad_remover: to mask out padding in convolutional layers (efficiency). Returns: the output tensor """ with tf.variable_scope("ffn"): if hparams.transformer_ffn_type == "fc": y = transformer.transformer_ffn_layer( common_layers.layer_preprocess(x, hparams), hparams, pad_remover, conv_padding="SAME", nonpadding_mask=nonpadding_mask) if hparams.transformer_ffn_type == "sepconv": assert nonpadding_mask is not None, ( "The nonpadding_mask should be provided, otherwise the model uses " "the leaked padding information to estimate the length!") y = common_layers.sepconv_relu_sepconv( common_layers.layer_preprocess(x, hparams), filter_size=hparams.filter_size, output_size=hparams.hidden_size, first_kernel_size=(3, 1), second_kernel_size=(5, 1), padding="SAME", nonpadding_mask=nonpadding_mask, dropout=hparams.relu_dropout) x = common_layers.layer_postprocess(x, y, hparams) return x
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 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 generally only need this mask for "packed" datasets, because for ordinary datasets, no padding is ever followed by nonpadding. pad_remover: to mask out padding in convolutional layers (efficiency). Returns: the output tensor """ with tf.variable_scope("ffn"): if hparams.transformer_ffn_type == "fc": y = transformer.transformer_ffn_layer( common_layers.layer_preprocess(x, hparams), hparams, pad_remover, conv_padding="SAME", nonpadding_mask=nonpadding_mask) if hparams.transformer_ffn_type == "sepconv": assert nonpadding_mask is not None, ( "The nonpadding_mask should be provided, otherwise the model uses " "the leaked padding information to estimate the length!") y = common_layers.sepconv_relu_sepconv( common_layers.layer_preprocess(x, hparams), filter_size=hparams.filter_size, output_size=hparams.hidden_size, first_kernel_size=(3, 1), second_kernel_size=(5, 1), padding="SAME", nonpadding_mask=nonpadding_mask, dropout=hparams.relu_dropout) x = common_layers.layer_postprocess(x, y, hparams) return x
[ "def", "transformer_encoder_ffn_unit", "(", "x", ",", "hparams", ",", "nonpadding_mask", "=", "None", ",", "pad_remover", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"ffn\"", ")", ":", "if", "hparams", ".", "transformer_ffn_type", "==", "\"fc\"", ":", "y", "=", "transformer", ".", "transformer_ffn_layer", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "hparams", ",", "pad_remover", ",", "conv_padding", "=", "\"SAME\"", ",", "nonpadding_mask", "=", "nonpadding_mask", ")", "if", "hparams", ".", "transformer_ffn_type", "==", "\"sepconv\"", ":", "assert", "nonpadding_mask", "is", "not", "None", ",", "(", "\"The nonpadding_mask should be provided, otherwise the model uses \"", "\"the leaked padding information to estimate the length!\"", ")", "y", "=", "common_layers", ".", "sepconv_relu_sepconv", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "filter_size", "=", "hparams", ".", "filter_size", ",", "output_size", "=", "hparams", ".", "hidden_size", ",", "first_kernel_size", "=", "(", "3", ",", "1", ")", ",", "second_kernel_size", "=", "(", "5", ",", "1", ")", ",", "padding", "=", "\"SAME\"", ",", "nonpadding_mask", "=", "nonpadding_mask", ",", "dropout", "=", "hparams", ".", "relu_dropout", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "return", "x" ]
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 generally only need this mask for "packed" datasets, because for ordinary datasets, no padding is ever followed by nonpadding. pad_remover: to mask out padding in convolutional layers (efficiency). Returns: the output tensor
[ "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, make_image_summary=True): """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 during training save_weights_to: an optional dictionary to capture attention weights for visualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: the output tensor """ with tf.variable_scope("self_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), None, encoder_self_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout, attention_type=hparams.self_attention_type, save_weights_to=save_weights_to, max_relative_position=hparams.max_relative_position, make_image_summary=make_image_summary, dropout_broadcast_dims=attention_dropout_broadcast_dims, hard_attention_k=hparams.hard_attention_k) x = common_layers.layer_postprocess(x, y, hparams) return x
python
def transformer_encoder_attention_unit(x, hparams, encoder_self_attention_bias, attention_dropout_broadcast_dims, save_weights_to=None, make_image_summary=True): """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 during training save_weights_to: an optional dictionary to capture attention weights for visualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: the output tensor """ with tf.variable_scope("self_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), None, encoder_self_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout, attention_type=hparams.self_attention_type, save_weights_to=save_weights_to, max_relative_position=hparams.max_relative_position, make_image_summary=make_image_summary, dropout_broadcast_dims=attention_dropout_broadcast_dims, hard_attention_k=hparams.hard_attention_k) x = common_layers.layer_postprocess(x, y, hparams) return x
[ "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", "(", "\"self_attention\"", ")", ":", "y", "=", "common_attention", ".", "multihead_attention", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "None", ",", "encoder_self_attention_bias", ",", "hparams", ".", "attention_key_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "attention_value_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "hidden_size", ",", "hparams", ".", "num_heads", ",", "hparams", ".", "attention_dropout", ",", "attention_type", "=", "hparams", ".", "self_attention_type", ",", "save_weights_to", "=", "save_weights_to", ",", "max_relative_position", "=", "hparams", ".", "max_relative_position", ",", "make_image_summary", "=", "make_image_summary", ",", "dropout_broadcast_dims", "=", "attention_dropout_broadcast_dims", ",", "hard_attention_k", "=", "hparams", ".", "hard_attention_k", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "return", "x" ]
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 during training save_weights_to: an optional dictionary to capture attention weights for visualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: the output tensor
[ "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, attention_dropout_broadcast_dims, save_weights_to=None, make_image_summary=True): """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-attention. [batch_size, decoder_length] encoder_decoder_attention_bias: Bias and mask weights for encoder-decoder attention. [batch_size, input_length] attention_dropout_broadcast_dims: Fpr noise broadcasting in the dropout layers to save memory during training save_weights_to: an optional dictionary to capture attention weights for visualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: The output tensor """ with tf.variable_scope("self_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), None, decoder_self_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout, attention_type=hparams.self_attention_type, save_weights_to=save_weights_to, max_relative_position=hparams.max_relative_position, cache=None, make_image_summary=make_image_summary, dropout_broadcast_dims=attention_dropout_broadcast_dims, hard_attention_k=hparams.hard_attention_k) x = common_layers.layer_postprocess(x, y, hparams) if encoder_output is not None: with tf.variable_scope("encdec_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), encoder_output, encoder_decoder_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout, save_weights_to=save_weights_to, make_image_summary=make_image_summary, dropout_broadcast_dims=attention_dropout_broadcast_dims, hard_attention_k=hparams.hard_attention_k) x = common_layers.layer_postprocess(x, y, hparams) return x
python
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=True): """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-attention. [batch_size, decoder_length] encoder_decoder_attention_bias: Bias and mask weights for encoder-decoder attention. [batch_size, input_length] attention_dropout_broadcast_dims: Fpr noise broadcasting in the dropout layers to save memory during training save_weights_to: an optional dictionary to capture attention weights for visualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: The output tensor """ with tf.variable_scope("self_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), None, decoder_self_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout, attention_type=hparams.self_attention_type, save_weights_to=save_weights_to, max_relative_position=hparams.max_relative_position, cache=None, make_image_summary=make_image_summary, dropout_broadcast_dims=attention_dropout_broadcast_dims, hard_attention_k=hparams.hard_attention_k) x = common_layers.layer_postprocess(x, y, hparams) if encoder_output is not None: with tf.variable_scope("encdec_attention"): y = common_attention.multihead_attention( common_layers.layer_preprocess(x, hparams), encoder_output, encoder_decoder_attention_bias, hparams.attention_key_channels or hparams.hidden_size, hparams.attention_value_channels or hparams.hidden_size, hparams.hidden_size, hparams.num_heads, hparams.attention_dropout, save_weights_to=save_weights_to, make_image_summary=make_image_summary, dropout_broadcast_dims=attention_dropout_broadcast_dims, hard_attention_k=hparams.hard_attention_k) x = common_layers.layer_postprocess(x, y, hparams) return x
[ "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", "=", "True", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"self_attention\"", ")", ":", "y", "=", "common_attention", ".", "multihead_attention", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "None", ",", "decoder_self_attention_bias", ",", "hparams", ".", "attention_key_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "attention_value_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "hidden_size", ",", "hparams", ".", "num_heads", ",", "hparams", ".", "attention_dropout", ",", "attention_type", "=", "hparams", ".", "self_attention_type", ",", "save_weights_to", "=", "save_weights_to", ",", "max_relative_position", "=", "hparams", ".", "max_relative_position", ",", "cache", "=", "None", ",", "make_image_summary", "=", "make_image_summary", ",", "dropout_broadcast_dims", "=", "attention_dropout_broadcast_dims", ",", "hard_attention_k", "=", "hparams", ".", "hard_attention_k", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "if", "encoder_output", "is", "not", "None", ":", "with", "tf", ".", "variable_scope", "(", "\"encdec_attention\"", ")", ":", "y", "=", "common_attention", ".", "multihead_attention", "(", "common_layers", ".", "layer_preprocess", "(", "x", ",", "hparams", ")", ",", "encoder_output", ",", "encoder_decoder_attention_bias", ",", "hparams", ".", "attention_key_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "attention_value_channels", "or", "hparams", ".", "hidden_size", ",", "hparams", ".", "hidden_size", ",", "hparams", ".", "num_heads", ",", "hparams", ".", "attention_dropout", ",", "save_weights_to", "=", "save_weights_to", ",", "make_image_summary", "=", "make_image_summary", ",", "dropout_broadcast_dims", "=", "attention_dropout_broadcast_dims", ",", "hard_attention_k", "=", "hparams", ".", "hard_attention_k", ")", "x", "=", "common_layers", ".", "layer_postprocess", "(", "x", ",", "y", ",", "hparams", ")", "return", "x" ]
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-attention. [batch_size, decoder_length] encoder_decoder_attention_bias: Bias and mask weights for encoder-decoder attention. [batch_size, input_length] attention_dropout_broadcast_dims: Fpr noise broadcasting in the dropout layers to save memory during training save_weights_to: an optional dictionary to capture attention weights for visualization; the weights tensor will be appended there under a string key created from the variable scope (including name). make_image_summary: Whether to make an attention image summary. Returns: The output tensor
[ "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 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: layer_inputs: - state: state step: indicates number of steps taken so far hparams: model hyper-parameters ffn_unit: feed-forward unit attention_unit: multi-head attention unit Returns: layer_output: new_state: new state """ state, inputs, memory = tf.unstack(layer_inputs, num=None, axis=0, name="unstack") new_state = step_preprocess(state, step, hparams) for i in range(hparams.num_inrecurrence_layers): with tf.variable_scope("rec_layer_%d" % i): new_state = ffn_unit(attention_unit(new_state)) return new_state, inputs, memory
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 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: layer_inputs: - state: state step: indicates number of steps taken so far hparams: model hyper-parameters ffn_unit: feed-forward unit attention_unit: multi-head attention unit Returns: layer_output: new_state: new state """ state, inputs, memory = tf.unstack(layer_inputs, num=None, axis=0, name="unstack") new_state = step_preprocess(state, step, hparams) for i in range(hparams.num_inrecurrence_layers): with tf.variable_scope("rec_layer_%d" % i): new_state = ffn_unit(attention_unit(new_state)) return new_state, inputs, memory
[ "def", "universal_transformer_basic", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ")", ":", "state", ",", "inputs", ",", "memory", "=", "tf", ".", "unstack", "(", "layer_inputs", ",", "num", "=", "None", ",", "axis", "=", "0", ",", "name", "=", "\"unstack\"", ")", "new_state", "=", "step_preprocess", "(", "state", ",", "step", ",", "hparams", ")", "for", "i", "in", "range", "(", "hparams", ".", "num_inrecurrence_layers", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"rec_layer_%d\"", "%", "i", ")", ":", "new_state", "=", "ffn_unit", "(", "attention_unit", "(", "new_state", ")", ")", "return", "new_state", ",", "inputs", ",", "memory" ]
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: layer_inputs: - state: state step: indicates number of steps taken so far hparams: model hyper-parameters ffn_unit: feed-forward unit attention_unit: multi-head attention unit Returns: layer_output: new_state: new state
[ "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 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 observation: Controlling the cary/transform gate with the original inputs works usually better (i.e. hparams.gates_inputs="i") Args: layer_inputs: - state: state - inputs: the original embedded inputs (= inputs to the first step) step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: the original embedded inputs (= inputs to the first step) """ state, inputs, memory = layer_inputs new_state = step_preprocess(state, step, hparams) for i in range(hparams.num_inrecurrence_layers): with tf.variable_scope("rec_layer_%d" % i): new_state = ffn_unit(attention_unit(new_state)) transformed_state = new_state gate_inputs = [] if "s" in hparams.gates_inputs: gate_inputs.append(state) if "t" in hparams.gates_inputs: gate_inputs.append(transformed_state) if "i" in hparams.gates_inputs: gate_inputs.append(inputs) gate_ffn_layer = hparams.gate_ffn_layer transform_gate = _ffn_layer_multi_inputs( gate_inputs, hparams, ffn_layer_type=gate_ffn_layer, name="transform", bias_initializer=tf.constant_initializer(hparams.transform_bias_init), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=True, postprocess=True) if hparams.couple_carry_transform_gates: carry_gate = tf.subtract(1.0, transform_gate, name="carry") else: carry_gate = _ffn_layer_multi_inputs( gate_inputs, hparams, ffn_layer_type=gate_ffn_layer, name="carry", bias_initializer=tf.constant_initializer(-hparams.transform_bias_init), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=True, postprocess=True) new_state = state * carry_gate + transformed_state * transform_gate tf.contrib.summary.scalar("highway_transform_gate_layer", tf.reduce_mean(transform_gate)) tf.contrib.summary.scalar("highway_carry_gate_layer", tf.reduce_mean(carry_gate)) return new_state, inputs, memory
python
def universal_transformer_highway(layer_inputs, step, hparams, ffn_unit, attention_unit, pad_remover=None): """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 observation: Controlling the cary/transform gate with the original inputs works usually better (i.e. hparams.gates_inputs="i") Args: layer_inputs: - state: state - inputs: the original embedded inputs (= inputs to the first step) step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: the original embedded inputs (= inputs to the first step) """ state, inputs, memory = layer_inputs new_state = step_preprocess(state, step, hparams) for i in range(hparams.num_inrecurrence_layers): with tf.variable_scope("rec_layer_%d" % i): new_state = ffn_unit(attention_unit(new_state)) transformed_state = new_state gate_inputs = [] if "s" in hparams.gates_inputs: gate_inputs.append(state) if "t" in hparams.gates_inputs: gate_inputs.append(transformed_state) if "i" in hparams.gates_inputs: gate_inputs.append(inputs) gate_ffn_layer = hparams.gate_ffn_layer transform_gate = _ffn_layer_multi_inputs( gate_inputs, hparams, ffn_layer_type=gate_ffn_layer, name="transform", bias_initializer=tf.constant_initializer(hparams.transform_bias_init), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=True, postprocess=True) if hparams.couple_carry_transform_gates: carry_gate = tf.subtract(1.0, transform_gate, name="carry") else: carry_gate = _ffn_layer_multi_inputs( gate_inputs, hparams, ffn_layer_type=gate_ffn_layer, name="carry", bias_initializer=tf.constant_initializer(-hparams.transform_bias_init), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=True, postprocess=True) new_state = state * carry_gate + transformed_state * transform_gate tf.contrib.summary.scalar("highway_transform_gate_layer", tf.reduce_mean(transform_gate)) tf.contrib.summary.scalar("highway_carry_gate_layer", tf.reduce_mean(carry_gate)) return new_state, inputs, memory
[ "def", "universal_transformer_highway", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "state", ",", "inputs", ",", "memory", "=", "layer_inputs", "new_state", "=", "step_preprocess", "(", "state", ",", "step", ",", "hparams", ")", "for", "i", "in", "range", "(", "hparams", ".", "num_inrecurrence_layers", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"rec_layer_%d\"", "%", "i", ")", ":", "new_state", "=", "ffn_unit", "(", "attention_unit", "(", "new_state", ")", ")", "transformed_state", "=", "new_state", "gate_inputs", "=", "[", "]", "if", "\"s\"", "in", "hparams", ".", "gates_inputs", ":", "gate_inputs", ".", "append", "(", "state", ")", "if", "\"t\"", "in", "hparams", ".", "gates_inputs", ":", "gate_inputs", ".", "append", "(", "transformed_state", ")", "if", "\"i\"", "in", "hparams", ".", "gates_inputs", ":", "gate_inputs", ".", "append", "(", "inputs", ")", "gate_ffn_layer", "=", "hparams", ".", "gate_ffn_layer", "transform_gate", "=", "_ffn_layer_multi_inputs", "(", "gate_inputs", ",", "hparams", ",", "ffn_layer_type", "=", "gate_ffn_layer", ",", "name", "=", "\"transform\"", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "hparams", ".", "transform_bias_init", ")", ",", "activation", "=", "tf", ".", "sigmoid", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "True", ",", "postprocess", "=", "True", ")", "if", "hparams", ".", "couple_carry_transform_gates", ":", "carry_gate", "=", "tf", ".", "subtract", "(", "1.0", ",", "transform_gate", ",", "name", "=", "\"carry\"", ")", "else", ":", "carry_gate", "=", "_ffn_layer_multi_inputs", "(", "gate_inputs", ",", "hparams", ",", "ffn_layer_type", "=", "gate_ffn_layer", ",", "name", "=", "\"carry\"", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "-", "hparams", ".", "transform_bias_init", ")", ",", "activation", "=", "tf", ".", "sigmoid", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "True", ",", "postprocess", "=", "True", ")", "new_state", "=", "state", "*", "carry_gate", "+", "transformed_state", "*", "transform_gate", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "\"highway_transform_gate_layer\"", ",", "tf", ".", "reduce_mean", "(", "transform_gate", ")", ")", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "\"highway_carry_gate_layer\"", ",", "tf", ".", "reduce_mean", "(", "carry_gate", ")", ")", "return", "new_state", ",", "inputs", ",", "memory" ]
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 observation: Controlling the cary/transform gate with the original inputs works usually better (i.e. hparams.gates_inputs="i") Args: layer_inputs: - state: state - inputs: the original embedded inputs (= inputs to the first step) step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: the original embedded inputs (= inputs to the first step)
[ "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 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 take so far hparams: model hyper-parameters. ffn_unit: feed-forward unit attention_unit: multi-head attention unit Returns: layer_output: new_state: new state memory: contains states from all the previous steps. """ _, inputs, memory = layer_inputs all_states = memory # add depth signal if hparams.depth_embedding: all_states = add_depth_embedding(all_states) # get the states up to the current step (non-zero part of the memory) states_so_far = all_states[:step, :, :, :] states_so_far_weights = tf.nn.softmax( common_layers.dense( states_so_far, (hparams.hidden_size if hparams.dwa_elements else 1), activation=None, use_bias=True), axis=-1) # prepare the state tensor that will be transformed state_to_be_transformed = tf.reduce_sum( (states_so_far * states_so_far_weights), axis=0) new_state = step_preprocess(state_to_be_transformed, step, hparams) for i in range(hparams.num_inrecurrence_layers): with tf.variable_scope("rec_layer_%d" % i): new_state = ffn_unit(attention_unit(new_state)) # add the new state to the memory memory = fill_memory_slot(memory, new_state, step + 1) return new_state, inputs, memory
python
def universal_transformer_depthwise_attention(layer_inputs, step, hparams, ffn_unit, attention_unit): """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 take so far hparams: model hyper-parameters. ffn_unit: feed-forward unit attention_unit: multi-head attention unit Returns: layer_output: new_state: new state memory: contains states from all the previous steps. """ _, inputs, memory = layer_inputs all_states = memory # add depth signal if hparams.depth_embedding: all_states = add_depth_embedding(all_states) # get the states up to the current step (non-zero part of the memory) states_so_far = all_states[:step, :, :, :] states_so_far_weights = tf.nn.softmax( common_layers.dense( states_so_far, (hparams.hidden_size if hparams.dwa_elements else 1), activation=None, use_bias=True), axis=-1) # prepare the state tensor that will be transformed state_to_be_transformed = tf.reduce_sum( (states_so_far * states_so_far_weights), axis=0) new_state = step_preprocess(state_to_be_transformed, step, hparams) for i in range(hparams.num_inrecurrence_layers): with tf.variable_scope("rec_layer_%d" % i): new_state = ffn_unit(attention_unit(new_state)) # add the new state to the memory memory = fill_memory_slot(memory, new_state, step + 1) return new_state, inputs, memory
[ "def", "universal_transformer_depthwise_attention", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ")", ":", "_", ",", "inputs", ",", "memory", "=", "layer_inputs", "all_states", "=", "memory", "# add depth signal", "if", "hparams", ".", "depth_embedding", ":", "all_states", "=", "add_depth_embedding", "(", "all_states", ")", "# get the states up to the current step (non-zero part of the memory)", "states_so_far", "=", "all_states", "[", ":", "step", ",", ":", ",", ":", ",", ":", "]", "states_so_far_weights", "=", "tf", ".", "nn", ".", "softmax", "(", "common_layers", ".", "dense", "(", "states_so_far", ",", "(", "hparams", ".", "hidden_size", "if", "hparams", ".", "dwa_elements", "else", "1", ")", ",", "activation", "=", "None", ",", "use_bias", "=", "True", ")", ",", "axis", "=", "-", "1", ")", "# prepare the state tensor that will be transformed", "state_to_be_transformed", "=", "tf", ".", "reduce_sum", "(", "(", "states_so_far", "*", "states_so_far_weights", ")", ",", "axis", "=", "0", ")", "new_state", "=", "step_preprocess", "(", "state_to_be_transformed", ",", "step", ",", "hparams", ")", "for", "i", "in", "range", "(", "hparams", ".", "num_inrecurrence_layers", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"rec_layer_%d\"", "%", "i", ")", ":", "new_state", "=", "ffn_unit", "(", "attention_unit", "(", "new_state", ")", ")", "# add the new state to the memory", "memory", "=", "fill_memory_slot", "(", "memory", ",", "new_state", ",", "step", "+", "1", ")", "return", "new_state", ",", "inputs", ",", "memory" ]
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 take so far hparams: model hyper-parameters. ffn_unit: feed-forward unit attention_unit: multi-head attention unit Returns: layer_output: new_state: new state memory: contains states from all the previous steps.
[ "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 of the information in depth, over different steps of the Universal Transformer. Args: layer_inputs: - state: state - inputs: not used here - memory: not used here step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: not uesed memory: not used """ state, unused_inputs, unused_memory = tf.unstack( layer_inputs, num=None, axis=0, name="unstack") # state (ut_state): output of the gru in the previous step # Multi_head_attention: assert not hparams.add_step_timing_signal # Let gru count for us! mh_attention_input = step_preprocess(state, step, hparams) transition_function_input = attention_unit(mh_attention_input) # Transition Function: if hparams.add_ffn_unit_to_the_transition_function: transition_function_input = ffn_unit(transition_function_input) transition_function_input = common_layers.layer_preprocess( transition_function_input, hparams) with tf.variable_scope("gru"): # gru update gate: z_t = sigmoid(W_z.x_t + U_z.h_{t-1}) transition_function_update_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="update", bias_initializer=tf.constant_initializer(1.0), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("gru_update_gate", tf.reduce_mean(transition_function_update_gate)) # gru reset gate: r_t = sigmoid(W_r.x_t + U_r.h_{t-1}) transition_function_reset_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="reset", bias_initializer=tf.constant_initializer(1.0), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("gru_reset_gate", tf.reduce_mean(transition_function_reset_gate)) reset_state = transition_function_reset_gate * state # gru_candidate_activation: h' = tanh(W_{x_t} + U (r_t h_{t-1}) transition_function_candidate = _ffn_layer_multi_inputs( [transition_function_input, reset_state], hparams, name="candidate", bias_initializer=tf.zeros_initializer(), activation=tf.tanh, pad_remover=pad_remover, preprocess=False, postprocess=False) transition_function_output = ( (1 - transition_function_update_gate) * transition_function_input + transition_function_update_gate * transition_function_candidate) transition_function_output = common_layers.layer_preprocess( transition_function_output, hparams) return transition_function_output, unused_inputs, unused_memory
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 of the information in depth, over different steps of the Universal Transformer. Args: layer_inputs: - state: state - inputs: not used here - memory: not used here step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: not uesed memory: not used """ state, unused_inputs, unused_memory = tf.unstack( layer_inputs, num=None, axis=0, name="unstack") # state (ut_state): output of the gru in the previous step # Multi_head_attention: assert not hparams.add_step_timing_signal # Let gru count for us! mh_attention_input = step_preprocess(state, step, hparams) transition_function_input = attention_unit(mh_attention_input) # Transition Function: if hparams.add_ffn_unit_to_the_transition_function: transition_function_input = ffn_unit(transition_function_input) transition_function_input = common_layers.layer_preprocess( transition_function_input, hparams) with tf.variable_scope("gru"): # gru update gate: z_t = sigmoid(W_z.x_t + U_z.h_{t-1}) transition_function_update_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="update", bias_initializer=tf.constant_initializer(1.0), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("gru_update_gate", tf.reduce_mean(transition_function_update_gate)) # gru reset gate: r_t = sigmoid(W_r.x_t + U_r.h_{t-1}) transition_function_reset_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="reset", bias_initializer=tf.constant_initializer(1.0), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("gru_reset_gate", tf.reduce_mean(transition_function_reset_gate)) reset_state = transition_function_reset_gate * state # gru_candidate_activation: h' = tanh(W_{x_t} + U (r_t h_{t-1}) transition_function_candidate = _ffn_layer_multi_inputs( [transition_function_input, reset_state], hparams, name="candidate", bias_initializer=tf.zeros_initializer(), activation=tf.tanh, pad_remover=pad_remover, preprocess=False, postprocess=False) transition_function_output = ( (1 - transition_function_update_gate) * transition_function_input + transition_function_update_gate * transition_function_candidate) transition_function_output = common_layers.layer_preprocess( transition_function_output, hparams) return transition_function_output, unused_inputs, unused_memory
[ "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", ".", "unstack", "(", "layer_inputs", ",", "num", "=", "None", ",", "axis", "=", "0", ",", "name", "=", "\"unstack\"", ")", "# state (ut_state): output of the gru in the previous step", "# Multi_head_attention:", "assert", "not", "hparams", ".", "add_step_timing_signal", "# Let gru count for us!", "mh_attention_input", "=", "step_preprocess", "(", "state", ",", "step", ",", "hparams", ")", "transition_function_input", "=", "attention_unit", "(", "mh_attention_input", ")", "# Transition Function:", "if", "hparams", ".", "add_ffn_unit_to_the_transition_function", ":", "transition_function_input", "=", "ffn_unit", "(", "transition_function_input", ")", "transition_function_input", "=", "common_layers", ".", "layer_preprocess", "(", "transition_function_input", ",", "hparams", ")", "with", "tf", ".", "variable_scope", "(", "\"gru\"", ")", ":", "# gru update gate: z_t = sigmoid(W_z.x_t + U_z.h_{t-1})", "transition_function_update_gate", "=", "_ffn_layer_multi_inputs", "(", "[", "transition_function_input", ",", "state", "]", ",", "hparams", ",", "name", "=", "\"update\"", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "1.0", ")", ",", "activation", "=", "tf", ".", "sigmoid", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "\"gru_update_gate\"", ",", "tf", ".", "reduce_mean", "(", "transition_function_update_gate", ")", ")", "# gru reset gate: r_t = sigmoid(W_r.x_t + U_r.h_{t-1})", "transition_function_reset_gate", "=", "_ffn_layer_multi_inputs", "(", "[", "transition_function_input", ",", "state", "]", ",", "hparams", ",", "name", "=", "\"reset\"", ",", "bias_initializer", "=", "tf", ".", "constant_initializer", "(", "1.0", ")", ",", "activation", "=", "tf", ".", "sigmoid", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "\"gru_reset_gate\"", ",", "tf", ".", "reduce_mean", "(", "transition_function_reset_gate", ")", ")", "reset_state", "=", "transition_function_reset_gate", "*", "state", "# gru_candidate_activation: h' = tanh(W_{x_t} + U (r_t h_{t-1})", "transition_function_candidate", "=", "_ffn_layer_multi_inputs", "(", "[", "transition_function_input", ",", "reset_state", "]", ",", "hparams", ",", "name", "=", "\"candidate\"", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "activation", "=", "tf", ".", "tanh", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", "transition_function_output", "=", "(", "(", "1", "-", "transition_function_update_gate", ")", "*", "transition_function_input", "+", "transition_function_update_gate", "*", "transition_function_candidate", ")", "transition_function_output", "=", "common_layers", ".", "layer_preprocess", "(", "transition_function_output", ",", "hparams", ")", "return", "transition_function_output", ",", "unused_inputs", ",", "unused_memory" ]
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 - inputs: not used here - memory: not used here step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: not uesed memory: not used
[ "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 flow of the information in depth, over different steps of the Universal Transformer. Args: layer_inputs: - state: state - inputs: the original embedded inputs (= inputs to the first step) - memory: memory used in lstm. step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: the original embedded inputs (= inputs to the first step) memory: contains information of state from all the previous steps. """ state, unused_inputs, memory = tf.unstack( layer_inputs, num=None, axis=0, name="unstack") # NOTE: # state (ut_state): output of the lstm in the previous step # inputs (ut_input): original input --> we don't use it here # memory: lstm memory # Multi_head_attention: assert not hparams.add_step_timing_signal # Let lstm count for us! mh_attention_input = step_preprocess(state, step, hparams) transition_function_input = attention_unit(mh_attention_input) # Transition Function: if hparams.add_ffn_unit_to_the_transition_function: transition_function_input = ffn_unit(transition_function_input) transition_function_input = common_layers.layer_preprocess( transition_function_input, hparams) with tf.variable_scope("lstm"): # lstm input gate: i_t = sigmoid(W_i.x_t + U_i.h_{t-1}) transition_function_input_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="input", bias_initializer=tf.zeros_initializer(), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("lstm_input_gate", tf.reduce_mean(transition_function_input_gate)) # lstm forget gate: f_t = sigmoid(W_f.x_t + U_f.h_{t-1}) transition_function_forget_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="forget", bias_initializer=tf.zeros_initializer(), activation=None, pad_remover=pad_remover, preprocess=False, postprocess=False) forget_bias_tensor = tf.constant(hparams.lstm_forget_bias) transition_function_forget_gate = tf.sigmoid( transition_function_forget_gate + forget_bias_tensor) tf.contrib.summary.scalar("lstm_forget_gate", tf.reduce_mean(transition_function_forget_gate)) # lstm output gate: o_t = sigmoid(W_o.x_t + U_o.h_{t-1}) transition_function_output_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="output", bias_initializer=tf.zeros_initializer(), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("lstm_output_gate", tf.reduce_mean(transition_function_output_gate)) # lstm input modulation transition_function_input_modulation = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="input_modulation", bias_initializer=tf.zeros_initializer(), activation=tf.tanh, pad_remover=pad_remover, preprocess=False, postprocess=False) transition_function_memory = ( memory * transition_function_forget_gate + transition_function_input_gate * transition_function_input_modulation) transition_function_output = ( tf.tanh(transition_function_memory) * transition_function_output_gate) transition_function_output = common_layers.layer_preprocess( transition_function_output, hparams) return transition_function_output, unused_inputs, transition_function_memory
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 flow of the information in depth, over different steps of the Universal Transformer. Args: layer_inputs: - state: state - inputs: the original embedded inputs (= inputs to the first step) - memory: memory used in lstm. step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: the original embedded inputs (= inputs to the first step) memory: contains information of state from all the previous steps. """ state, unused_inputs, memory = tf.unstack( layer_inputs, num=None, axis=0, name="unstack") # NOTE: # state (ut_state): output of the lstm in the previous step # inputs (ut_input): original input --> we don't use it here # memory: lstm memory # Multi_head_attention: assert not hparams.add_step_timing_signal # Let lstm count for us! mh_attention_input = step_preprocess(state, step, hparams) transition_function_input = attention_unit(mh_attention_input) # Transition Function: if hparams.add_ffn_unit_to_the_transition_function: transition_function_input = ffn_unit(transition_function_input) transition_function_input = common_layers.layer_preprocess( transition_function_input, hparams) with tf.variable_scope("lstm"): # lstm input gate: i_t = sigmoid(W_i.x_t + U_i.h_{t-1}) transition_function_input_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="input", bias_initializer=tf.zeros_initializer(), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("lstm_input_gate", tf.reduce_mean(transition_function_input_gate)) # lstm forget gate: f_t = sigmoid(W_f.x_t + U_f.h_{t-1}) transition_function_forget_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="forget", bias_initializer=tf.zeros_initializer(), activation=None, pad_remover=pad_remover, preprocess=False, postprocess=False) forget_bias_tensor = tf.constant(hparams.lstm_forget_bias) transition_function_forget_gate = tf.sigmoid( transition_function_forget_gate + forget_bias_tensor) tf.contrib.summary.scalar("lstm_forget_gate", tf.reduce_mean(transition_function_forget_gate)) # lstm output gate: o_t = sigmoid(W_o.x_t + U_o.h_{t-1}) transition_function_output_gate = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="output", bias_initializer=tf.zeros_initializer(), activation=tf.sigmoid, pad_remover=pad_remover, preprocess=False, postprocess=False) tf.contrib.summary.scalar("lstm_output_gate", tf.reduce_mean(transition_function_output_gate)) # lstm input modulation transition_function_input_modulation = _ffn_layer_multi_inputs( [transition_function_input, state], hparams, name="input_modulation", bias_initializer=tf.zeros_initializer(), activation=tf.tanh, pad_remover=pad_remover, preprocess=False, postprocess=False) transition_function_memory = ( memory * transition_function_forget_gate + transition_function_input_gate * transition_function_input_modulation) transition_function_output = ( tf.tanh(transition_function_memory) * transition_function_output_gate) transition_function_output = common_layers.layer_preprocess( transition_function_output, hparams) return transition_function_output, unused_inputs, transition_function_memory
[ "def", "universal_transformer_with_lstm_as_transition_function", "(", "layer_inputs", ",", "step", ",", "hparams", ",", "ffn_unit", ",", "attention_unit", ",", "pad_remover", "=", "None", ")", ":", "state", ",", "unused_inputs", ",", "memory", "=", "tf", ".", "unstack", "(", "layer_inputs", ",", "num", "=", "None", ",", "axis", "=", "0", ",", "name", "=", "\"unstack\"", ")", "# NOTE:", "# state (ut_state): output of the lstm in the previous step", "# inputs (ut_input): original input --> we don't use it here", "# memory: lstm memory", "# Multi_head_attention:", "assert", "not", "hparams", ".", "add_step_timing_signal", "# Let lstm count for us!", "mh_attention_input", "=", "step_preprocess", "(", "state", ",", "step", ",", "hparams", ")", "transition_function_input", "=", "attention_unit", "(", "mh_attention_input", ")", "# Transition Function:", "if", "hparams", ".", "add_ffn_unit_to_the_transition_function", ":", "transition_function_input", "=", "ffn_unit", "(", "transition_function_input", ")", "transition_function_input", "=", "common_layers", ".", "layer_preprocess", "(", "transition_function_input", ",", "hparams", ")", "with", "tf", ".", "variable_scope", "(", "\"lstm\"", ")", ":", "# lstm input gate: i_t = sigmoid(W_i.x_t + U_i.h_{t-1})", "transition_function_input_gate", "=", "_ffn_layer_multi_inputs", "(", "[", "transition_function_input", ",", "state", "]", ",", "hparams", ",", "name", "=", "\"input\"", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "activation", "=", "tf", ".", "sigmoid", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "\"lstm_input_gate\"", ",", "tf", ".", "reduce_mean", "(", "transition_function_input_gate", ")", ")", "# lstm forget gate: f_t = sigmoid(W_f.x_t + U_f.h_{t-1})", "transition_function_forget_gate", "=", "_ffn_layer_multi_inputs", "(", "[", "transition_function_input", ",", "state", "]", ",", "hparams", ",", "name", "=", "\"forget\"", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "activation", "=", "None", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", "forget_bias_tensor", "=", "tf", ".", "constant", "(", "hparams", ".", "lstm_forget_bias", ")", "transition_function_forget_gate", "=", "tf", ".", "sigmoid", "(", "transition_function_forget_gate", "+", "forget_bias_tensor", ")", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "\"lstm_forget_gate\"", ",", "tf", ".", "reduce_mean", "(", "transition_function_forget_gate", ")", ")", "# lstm output gate: o_t = sigmoid(W_o.x_t + U_o.h_{t-1})", "transition_function_output_gate", "=", "_ffn_layer_multi_inputs", "(", "[", "transition_function_input", ",", "state", "]", ",", "hparams", ",", "name", "=", "\"output\"", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "activation", "=", "tf", ".", "sigmoid", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", "tf", ".", "contrib", ".", "summary", ".", "scalar", "(", "\"lstm_output_gate\"", ",", "tf", ".", "reduce_mean", "(", "transition_function_output_gate", ")", ")", "# lstm input modulation", "transition_function_input_modulation", "=", "_ffn_layer_multi_inputs", "(", "[", "transition_function_input", ",", "state", "]", ",", "hparams", ",", "name", "=", "\"input_modulation\"", ",", "bias_initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "activation", "=", "tf", ".", "tanh", ",", "pad_remover", "=", "pad_remover", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", "transition_function_memory", "=", "(", "memory", "*", "transition_function_forget_gate", "+", "transition_function_input_gate", "*", "transition_function_input_modulation", ")", "transition_function_output", "=", "(", "tf", ".", "tanh", "(", "transition_function_memory", ")", "*", "transition_function_output_gate", ")", "transition_function_output", "=", "common_layers", ".", "layer_preprocess", "(", "transition_function_output", ",", "hparams", ")", "return", "transition_function_output", ",", "unused_inputs", ",", "transition_function_memory" ]
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 - inputs: the original embedded inputs (= inputs to the first step) - memory: memory used in lstm. step: indicates number of steps taken so far 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: layer_output: new_state: new state inputs: the original embedded inputs (= inputs to the first step) memory: contains information of state from all the previous steps.
[ "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, pad_remover=None, preprocess=False, postprocess=False): """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 activation: activation function pad_remover: pad remover preprocess: if preprocess the input postprocess: if postprocess the output Returns: a tensor Raises: ValueError: Unknown ffn_layer type. """ # need at least one inputs num_inputs = len(inputs_list) assert num_inputs > 0 if preprocess and num_inputs == 1: inputs_list[0] = common_layers.layer_preprocess(inputs_list[0], hparams) if postprocess: original_inputs = inputs_list[0] # the output size is the hidden size of the main inputs main_input = inputs_list[0] original_shape = common_layers.shape_list(main_input) assert hparams.hidden_size == common_layers.shape_list(main_input)[-1] # all the inputs are in the same shape with main inputs for inputs in inputs_list: main_input.get_shape().assert_is_compatible_with(inputs.get_shape()) def remove_pads(x): original_shape = common_layers.shape_list(x) # Collapse `x` across examples, and remove padding positions. x = tf.reshape(x, tf.concat([[-1], original_shape[2:]], axis=0)) x = tf.expand_dims(pad_remover.remove(x), axis=0) return x if pad_remover: for i, inputs in enumerate(inputs_list): inputs_list[i] = remove_pads(inputs) ffn_inputs = inputs_list[0] if len(inputs_list) != 1: ffn_inputs = tf.concat(inputs_list, axis=-1) if ffn_layer_type == "dense": output = common_layers.dense( ffn_inputs, hparams.hidden_size, name=name, activation=activation, use_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer) elif ffn_layer_type == "dense_dropconnect": output = common_layers.dense_dropconnect( ffn_inputs, hparams.hidden_size, name=name, dropconnect_dropout=hparams.dropconnect_dropout, output_activation=activation) postprocess = False # no dropout on the output unit elif ffn_layer_type == "dense_relu_dense": output = common_layers.dense_relu_dense( ffn_inputs, hparams.filter_size, hparams.hidden_size, name=name, dropout=hparams.relu_dropout, output_activation=activation, ) else: raise ValueError("Unknown ffn_layer type: %s" % ffn_layer_type) if pad_remover: # Restore `output` to the original shape of `x`, including padding. output = tf.reshape( pad_remover.restore(tf.squeeze(output, axis=0)), original_shape) if postprocess: if num_inputs == 1: output = common_layers.layer_postprocess(original_inputs, output, hparams) else: # only dropout (no residual)x hp = copy.copy(hparams) hp.layer_postprocess_sequence = hp.layer_postprocess_sequence.replace( "a", "") output = common_layers.layer_postprocess(original_inputs, output, hp) return output
python
def _ffn_layer_multi_inputs(inputs_list, hparams, ffn_layer_type="dense", name="ffn", kernel_initializer=None, bias_initializer=None, activation=None, pad_remover=None, preprocess=False, postprocess=False): """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 activation: activation function pad_remover: pad remover preprocess: if preprocess the input postprocess: if postprocess the output Returns: a tensor Raises: ValueError: Unknown ffn_layer type. """ # need at least one inputs num_inputs = len(inputs_list) assert num_inputs > 0 if preprocess and num_inputs == 1: inputs_list[0] = common_layers.layer_preprocess(inputs_list[0], hparams) if postprocess: original_inputs = inputs_list[0] # the output size is the hidden size of the main inputs main_input = inputs_list[0] original_shape = common_layers.shape_list(main_input) assert hparams.hidden_size == common_layers.shape_list(main_input)[-1] # all the inputs are in the same shape with main inputs for inputs in inputs_list: main_input.get_shape().assert_is_compatible_with(inputs.get_shape()) def remove_pads(x): original_shape = common_layers.shape_list(x) # Collapse `x` across examples, and remove padding positions. x = tf.reshape(x, tf.concat([[-1], original_shape[2:]], axis=0)) x = tf.expand_dims(pad_remover.remove(x), axis=0) return x if pad_remover: for i, inputs in enumerate(inputs_list): inputs_list[i] = remove_pads(inputs) ffn_inputs = inputs_list[0] if len(inputs_list) != 1: ffn_inputs = tf.concat(inputs_list, axis=-1) if ffn_layer_type == "dense": output = common_layers.dense( ffn_inputs, hparams.hidden_size, name=name, activation=activation, use_bias=True, kernel_initializer=kernel_initializer, bias_initializer=bias_initializer) elif ffn_layer_type == "dense_dropconnect": output = common_layers.dense_dropconnect( ffn_inputs, hparams.hidden_size, name=name, dropconnect_dropout=hparams.dropconnect_dropout, output_activation=activation) postprocess = False # no dropout on the output unit elif ffn_layer_type == "dense_relu_dense": output = common_layers.dense_relu_dense( ffn_inputs, hparams.filter_size, hparams.hidden_size, name=name, dropout=hparams.relu_dropout, output_activation=activation, ) else: raise ValueError("Unknown ffn_layer type: %s" % ffn_layer_type) if pad_remover: # Restore `output` to the original shape of `x`, including padding. output = tf.reshape( pad_remover.restore(tf.squeeze(output, axis=0)), original_shape) if postprocess: if num_inputs == 1: output = common_layers.layer_postprocess(original_inputs, output, hparams) else: # only dropout (no residual)x hp = copy.copy(hparams) hp.layer_postprocess_sequence = hp.layer_postprocess_sequence.replace( "a", "") output = common_layers.layer_postprocess(original_inputs, output, hp) return output
[ "def", "_ffn_layer_multi_inputs", "(", "inputs_list", ",", "hparams", ",", "ffn_layer_type", "=", "\"dense\"", ",", "name", "=", "\"ffn\"", ",", "kernel_initializer", "=", "None", ",", "bias_initializer", "=", "None", ",", "activation", "=", "None", ",", "pad_remover", "=", "None", ",", "preprocess", "=", "False", ",", "postprocess", "=", "False", ")", ":", "# need at least one inputs", "num_inputs", "=", "len", "(", "inputs_list", ")", "assert", "num_inputs", ">", "0", "if", "preprocess", "and", "num_inputs", "==", "1", ":", "inputs_list", "[", "0", "]", "=", "common_layers", ".", "layer_preprocess", "(", "inputs_list", "[", "0", "]", ",", "hparams", ")", "if", "postprocess", ":", "original_inputs", "=", "inputs_list", "[", "0", "]", "# the output size is the hidden size of the main inputs", "main_input", "=", "inputs_list", "[", "0", "]", "original_shape", "=", "common_layers", ".", "shape_list", "(", "main_input", ")", "assert", "hparams", ".", "hidden_size", "==", "common_layers", ".", "shape_list", "(", "main_input", ")", "[", "-", "1", "]", "# all the inputs are in the same shape with main inputs", "for", "inputs", "in", "inputs_list", ":", "main_input", ".", "get_shape", "(", ")", ".", "assert_is_compatible_with", "(", "inputs", ".", "get_shape", "(", ")", ")", "def", "remove_pads", "(", "x", ")", ":", "original_shape", "=", "common_layers", ".", "shape_list", "(", "x", ")", "# Collapse `x` across examples, and remove padding positions.", "x", "=", "tf", ".", "reshape", "(", "x", ",", "tf", ".", "concat", "(", "[", "[", "-", "1", "]", ",", "original_shape", "[", "2", ":", "]", "]", ",", "axis", "=", "0", ")", ")", "x", "=", "tf", ".", "expand_dims", "(", "pad_remover", ".", "remove", "(", "x", ")", ",", "axis", "=", "0", ")", "return", "x", "if", "pad_remover", ":", "for", "i", ",", "inputs", "in", "enumerate", "(", "inputs_list", ")", ":", "inputs_list", "[", "i", "]", "=", "remove_pads", "(", "inputs", ")", "ffn_inputs", "=", "inputs_list", "[", "0", "]", "if", "len", "(", "inputs_list", ")", "!=", "1", ":", "ffn_inputs", "=", "tf", ".", "concat", "(", "inputs_list", ",", "axis", "=", "-", "1", ")", "if", "ffn_layer_type", "==", "\"dense\"", ":", "output", "=", "common_layers", ".", "dense", "(", "ffn_inputs", ",", "hparams", ".", "hidden_size", ",", "name", "=", "name", ",", "activation", "=", "activation", ",", "use_bias", "=", "True", ",", "kernel_initializer", "=", "kernel_initializer", ",", "bias_initializer", "=", "bias_initializer", ")", "elif", "ffn_layer_type", "==", "\"dense_dropconnect\"", ":", "output", "=", "common_layers", ".", "dense_dropconnect", "(", "ffn_inputs", ",", "hparams", ".", "hidden_size", ",", "name", "=", "name", ",", "dropconnect_dropout", "=", "hparams", ".", "dropconnect_dropout", ",", "output_activation", "=", "activation", ")", "postprocess", "=", "False", "# no dropout on the output unit", "elif", "ffn_layer_type", "==", "\"dense_relu_dense\"", ":", "output", "=", "common_layers", ".", "dense_relu_dense", "(", "ffn_inputs", ",", "hparams", ".", "filter_size", ",", "hparams", ".", "hidden_size", ",", "name", "=", "name", ",", "dropout", "=", "hparams", ".", "relu_dropout", ",", "output_activation", "=", "activation", ",", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown ffn_layer type: %s\"", "%", "ffn_layer_type", ")", "if", "pad_remover", ":", "# Restore `output` to the original shape of `x`, including padding.", "output", "=", "tf", ".", "reshape", "(", "pad_remover", ".", "restore", "(", "tf", ".", "squeeze", "(", "output", ",", "axis", "=", "0", ")", ")", ",", "original_shape", ")", "if", "postprocess", ":", "if", "num_inputs", "==", "1", ":", "output", "=", "common_layers", ".", "layer_postprocess", "(", "original_inputs", ",", "output", ",", "hparams", ")", "else", ":", "# only dropout (no residual)x", "hp", "=", "copy", ".", "copy", "(", "hparams", ")", "hp", ".", "layer_postprocess_sequence", "=", "hp", ".", "layer_postprocess_sequence", ".", "replace", "(", "\"a\"", ",", "\"\"", ")", "output", "=", "common_layers", ".", "layer_postprocess", "(", "original_inputs", ",", "output", ",", "hp", ")", "return", "output" ]
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 activation: activation function pad_remover: pad remover preprocess: if preprocess the input postprocess: if postprocess the output Returns: a tensor Raises: ValueError: Unknown ffn_layer type.
[ "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_size) Returns: filled memory """ mask = tf.to_float( tf.one_hot(index, tf.shape(memory)[0])[:, None, None, None]) fill_memory = (1 - mask) * memory + mask * value[None, ...] return fill_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_size) Returns: filled memory """ mask = tf.to_float( tf.one_hot(index, tf.shape(memory)[0])[:, None, None, None]) fill_memory = (1 - mask) * memory + mask * value[None, ...] return fill_memory
[ "def", "fill_memory_slot", "(", "memory", ",", "value", ",", "index", ")", ":", "mask", "=", "tf", ".", "to_float", "(", "tf", ".", "one_hot", "(", "index", ",", "tf", ".", "shape", "(", "memory", ")", "[", "0", "]", ")", "[", ":", ",", "None", ",", "None", ",", "None", "]", ")", "fill_memory", "=", "(", "1", "-", "mask", ")", "*", "memory", "+", "mask", "*", "value", "[", "None", ",", "...", "]", "return", "fill_memory" ]
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: x = add_position_timing_signal(x, step, hparams) if hparams.add_step_timing_signal: x = add_step_timing_signal(x, step, hparams) if ((hparams.add_position_timing_signal or hparams.add_position_timing_signal) and hparams.add_or_concat_timing_signal == "concat"): # linear projection to the original dimension of x x = common_layers.dense( x, original_channel_size, activation=None, use_bias=False) if hparams.add_sru: x = common_layers.sru(x) return x
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: x = add_position_timing_signal(x, step, hparams) if hparams.add_step_timing_signal: x = add_step_timing_signal(x, step, hparams) if ((hparams.add_position_timing_signal or hparams.add_position_timing_signal) and hparams.add_or_concat_timing_signal == "concat"): # linear projection to the original dimension of x x = common_layers.dense( x, original_channel_size, activation=None, use_bias=False) if hparams.add_sru: x = common_layers.sru(x) return x
[ "def", "step_preprocess", "(", "x", ",", "step", ",", "hparams", ")", ":", "original_channel_size", "=", "common_layers", ".", "shape_list", "(", "x", ")", "[", "-", "1", "]", "if", "hparams", ".", "add_position_timing_signal", ":", "x", "=", "add_position_timing_signal", "(", "x", ",", "step", ",", "hparams", ")", "if", "hparams", ".", "add_step_timing_signal", ":", "x", "=", "add_step_timing_signal", "(", "x", ",", "step", ",", "hparams", ")", "if", "(", "(", "hparams", ".", "add_position_timing_signal", "or", "hparams", ".", "add_position_timing_signal", ")", "and", "hparams", ".", "add_or_concat_timing_signal", "==", "\"concat\"", ")", ":", "# linear projection to the original dimension of x", "x", "=", "common_layers", ".", "dense", "(", "x", ",", "original_channel_size", ",", "activation", "=", "None", ",", "use_bias", "=", "False", ")", "if", "hparams", ".", "add_sru", ":", "x", "=", "common_layers", ".", "sru", "(", "x", ")", "return", "x" ]
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", ":", "continue", "yield", "record", "if", "take_ownership", ":", "f", ".", "close", "(", ")" ]
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", ")", "as", "f", ":", "for", "record", "in", "wet_records_from_file_obj", "(", "f", ")", ":", "yield", "record" ]
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, timestamp) duration = end - start duration_mins = duration.total_seconds() / 60 tf.logging.info('Total time [%s] (m): %d', name, int(duration_mins))
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, timestamp) duration = end - start duration_mins = duration.total_seconds() / 60 tf.logging.info('Total time [%s] (m): %d', name, int(duration_mins))
[ "def", "timing", "(", "name", "=", "''", ")", ":", "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", ",", "timestamp", ")", "duration", "=", "end", "-", "start", "duration_mins", "=", "duration", ".", "total_seconds", "(", ")", "/", "60", "tf", ".", "logging", ".", "info", "(", "'Total time [%s] (m): %d'", ",", "name", ",", "int", "(", "duration_mins", ")", ")" ]
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):].strip() line = f.readline() # Consume empty separator f.readline() # Read content length = int(line.split(':')[1]) return cls(url, length)
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):].strip() line = f.readline() # Consume empty separator f.readline() # Read content length = int(line.split(':')[1]) return cls(url, length)
[ "def", "read", "(", "cls", ",", "f", ")", ":", "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", ")", ":", "]", ".", "strip", "(", ")", "line", "=", "f", ".", "readline", "(", ")", "# Consume empty separator", "f", ".", "readline", "(", ")", "# Read content", "length", "=", "int", "(", "line", ".", "split", "(", "':'", ")", "[", "1", "]", ")", "return", "cls", "(", "url", ",", "length", ")" ]
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 empty separators", "f", ".", "readline", "(", ")", "f", ".", "readline", "(", ")", "return", "cls", "(", "header", ".", "url", ",", "content", ")" ]
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 += [layers.Dense(hidden_size), activation_fn()] cur_layers += [layers.Dense(num_output_classes), layers.LogSoftmax()] return layers.Serial(*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 += [layers.Dense(hidden_size), activation_fn()] cur_layers += [layers.Dense(num_output_classes), layers.LogSoftmax()] return layers.Serial(*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", "=", "[", "layers", ".", "Flatten", "(", ")", "]", "for", "_", "in", "range", "(", "num_hidden_layers", ")", ":", "cur_layers", "+=", "[", "layers", ".", "Dense", "(", "hidden_size", ")", ",", "activation_fn", "(", ")", "]", "cur_layers", "+=", "[", "layers", ".", "Dense", "(", "num_output_classes", ")", ",", "layers", ".", "LogSoftmax", "(", ")", "]", "return", "layers", ".", "Serial", "(", "*", "cur_layers", ")" ]
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 checking observation and action space " "compatibility across envs, since there is just one.") return # NOTE: We compare string representations of observation_space and # action_space because compositional classes like space.Tuple don't return # true on object comparison. if not all( str(env.observation_space) == str(self.observation_space) for env in self._envs): err_str = ("All environments should have the same observation space, but " "don't.") tf.logging.error(err_str) # Log all observation spaces. for i, env in enumerate(self._envs): tf.logging.error("Env[%d] has observation space [%s]", i, env.observation_space) raise ValueError(err_str) if not all( str(env.action_space) == str(self.action_space) for env in self._envs): err_str = "All environments should have the same action space, but don't." tf.logging.error(err_str) # Log all action spaces. for i, env in enumerate(self._envs): tf.logging.error("Env[%d] has action space [%s]", i, env.action_space) raise ValueError(err_str)
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 checking observation and action space " "compatibility across envs, since there is just one.") return # NOTE: We compare string representations of observation_space and # action_space because compositional classes like space.Tuple don't return # true on object comparison. if not all( str(env.observation_space) == str(self.observation_space) for env in self._envs): err_str = ("All environments should have the same observation space, but " "don't.") tf.logging.error(err_str) # Log all observation spaces. for i, env in enumerate(self._envs): tf.logging.error("Env[%d] has observation space [%s]", i, env.observation_space) raise ValueError(err_str) if not all( str(env.action_space) == str(self.action_space) for env in self._envs): err_str = "All environments should have the same action space, but don't." tf.logging.error(err_str) # Log all action spaces. for i, env in enumerate(self._envs): tf.logging.error("Env[%d] has action space [%s]", i, env.action_space) raise ValueError(err_str)
[ "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", ".", "_envs", ",", "list", ")", ":", "tf", ".", "logging", ".", "warning", "(", "\"Not checking observation and action space \"", "\"compatibility across envs, since there is just one.\"", ")", "return", "# NOTE: We compare string representations of observation_space and", "# action_space because compositional classes like space.Tuple don't return", "# true on object comparison.", "if", "not", "all", "(", "str", "(", "env", ".", "observation_space", ")", "==", "str", "(", "self", ".", "observation_space", ")", "for", "env", "in", "self", ".", "_envs", ")", ":", "err_str", "=", "(", "\"All environments should have the same observation space, but \"", "\"don't.\"", ")", "tf", ".", "logging", ".", "error", "(", "err_str", ")", "# Log all observation spaces.", "for", "i", ",", "env", "in", "enumerate", "(", "self", ".", "_envs", ")", ":", "tf", ".", "logging", ".", "error", "(", "\"Env[%d] has observation space [%s]\"", ",", "i", ",", "env", ".", "observation_space", ")", "raise", "ValueError", "(", "err_str", ")", "if", "not", "all", "(", "str", "(", "env", ".", "action_space", ")", "==", "str", "(", "self", ".", "action_space", ")", "for", "env", "in", "self", ".", "_envs", ")", ":", "err_str", "=", "\"All environments should have the same action space, but don't.\"", "tf", ".", "logging", ".", "error", "(", "err_str", ")", "# Log all action spaces.", "for", "i", ",", "env", "in", "enumerate", "(", "self", ".", "_envs", ")", ":", "tf", ".", "logging", ".", "error", "(", "\"Env[%d] has action space [%s]\"", ",", "i", ",", "env", ".", "action_space", ")", "raise", "ValueError", "(", "err_str", ")" ]
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__ anyways). Args: batch_size: (int) Number of `self.base_env_name` envs to initialize. """ assert batch_size >= 1 self._batch_size = batch_size self._envs = [gym.make(self.base_env_name) for _ in range(batch_size)] if self._env_wrapper_fn is not None: self._envs = list(map(self._env_wrapper_fn, self._envs)) # If self.observation_space and self.action_space aren't None, then it means # that this is a re-initialization of this class, in that case make sure # that this matches our previous behaviour. if self._observation_space: assert str(self._observation_space) == str( self._envs[0].observation_space) else: # This means that we are initializing this class for the first time. # # We set this equal to the first env's observation space, later on we'll # verify that all envs have the same observation space. self._observation_space = self._envs[0].observation_space # Similarly for action_space if self._action_space: assert str(self._action_space) == str(self._envs[0].action_space) else: self._action_space = self._envs[0].action_space self._verify_same_spaces() # If self.reward_range is None, i.e. this means that we should take the # reward range of the env. if self.reward_range is None: self._reward_range = self._envs[0].reward_range # This data structure stores the history of each env. # # NOTE: Even if the env is a NN and can step in all batches concurrently, it # is still valuable to store the trajectories separately. self._trajectories = trajectory.BatchTrajectory(batch_size=batch_size)
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__ anyways). Args: batch_size: (int) Number of `self.base_env_name` envs to initialize. """ assert batch_size >= 1 self._batch_size = batch_size self._envs = [gym.make(self.base_env_name) for _ in range(batch_size)] if self._env_wrapper_fn is not None: self._envs = list(map(self._env_wrapper_fn, self._envs)) # If self.observation_space and self.action_space aren't None, then it means # that this is a re-initialization of this class, in that case make sure # that this matches our previous behaviour. if self._observation_space: assert str(self._observation_space) == str( self._envs[0].observation_space) else: # This means that we are initializing this class for the first time. # # We set this equal to the first env's observation space, later on we'll # verify that all envs have the same observation space. self._observation_space = self._envs[0].observation_space # Similarly for action_space if self._action_space: assert str(self._action_space) == str(self._envs[0].action_space) else: self._action_space = self._envs[0].action_space self._verify_same_spaces() # If self.reward_range is None, i.e. this means that we should take the # reward range of the env. if self.reward_range is None: self._reward_range = self._envs[0].reward_range # This data structure stores the history of each env. # # NOTE: Even if the env is a NN and can step in all batches concurrently, it # is still valuable to store the trajectories separately. self._trajectories = trajectory.BatchTrajectory(batch_size=batch_size)
[ "def", "initialize_environments", "(", "self", ",", "batch_size", "=", "1", ")", ":", "assert", "batch_size", ">=", "1", "self", ".", "_batch_size", "=", "batch_size", "self", ".", "_envs", "=", "[", "gym", ".", "make", "(", "self", ".", "base_env_name", ")", "for", "_", "in", "range", "(", "batch_size", ")", "]", "if", "self", ".", "_env_wrapper_fn", "is", "not", "None", ":", "self", ".", "_envs", "=", "list", "(", "map", "(", "self", ".", "_env_wrapper_fn", ",", "self", ".", "_envs", ")", ")", "# If self.observation_space and self.action_space aren't None, then it means", "# that this is a re-initialization of this class, in that case make sure", "# that this matches our previous behaviour.", "if", "self", ".", "_observation_space", ":", "assert", "str", "(", "self", ".", "_observation_space", ")", "==", "str", "(", "self", ".", "_envs", "[", "0", "]", ".", "observation_space", ")", "else", ":", "# This means that we are initializing this class for the first time.", "#", "# We set this equal to the first env's observation space, later on we'll", "# verify that all envs have the same observation space.", "self", ".", "_observation_space", "=", "self", ".", "_envs", "[", "0", "]", ".", "observation_space", "# Similarly for action_space", "if", "self", ".", "_action_space", ":", "assert", "str", "(", "self", ".", "_action_space", ")", "==", "str", "(", "self", ".", "_envs", "[", "0", "]", ".", "action_space", ")", "else", ":", "self", ".", "_action_space", "=", "self", ".", "_envs", "[", "0", "]", ".", "action_space", "self", ".", "_verify_same_spaces", "(", ")", "# If self.reward_range is None, i.e. this means that we should take the", "# reward range of the env.", "if", "self", ".", "reward_range", "is", "None", ":", "self", ".", "_reward_range", "=", "self", ".", "_envs", "[", "0", "]", ".", "reward_range", "# This data structure stores the history of each env.", "#", "# NOTE: Even if the env is a NN and can step in all batches concurrently, it", "# is still valuable to store the trajectories separately.", "self", ".", "_trajectories", "=", "trajectory", ".", "BatchTrajectory", "(", "batch_size", "=", "batch_size", ")" ]
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.base_env_name` envs to initialize.
[ "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.clip(rewards, min_reward, max_reward) # Round to (nearest) int and convert to integral type. rewards = np.around(rewards, decimals=0).astype(np.int64) return rewards
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.clip(rewards, min_reward, max_reward) # Round to (nearest) int and convert to integral type. rewards = np.around(rewards, decimals=0).astype(np.int64) return rewards
[ "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", ")", "# Round to (nearest) int and convert to integral type.", "rewards", "=", "np", ".", "around", "(", "rewards", ",", "decimals", "=", "0", ")", ".", "astype", "(", "np", ".", "int64", ")", "return", "rewards" ]
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 rewards are discrete. if not self.is_reward_range_finite: tf.logging.error("Infinite reward range, `num_rewards returning None`") return None if not self.is_processed_rewards_discrete: tf.logging.error( "Processed rewards are not discrete, `num_rewards` returning None") return None min_reward, max_reward = self.reward_range return max_reward - min_reward + 1
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 rewards are discrete. if not self.is_reward_range_finite: tf.logging.error("Infinite reward range, `num_rewards returning None`") return None if not self.is_processed_rewards_discrete: tf.logging.error( "Processed rewards are not discrete, `num_rewards` returning None") return None min_reward, max_reward = self.reward_range return max_reward - min_reward + 1
[ "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_rewards returning None`\"", ")", "return", "None", "if", "not", "self", ".", "is_processed_rewards_discrete", ":", "tf", ".", "logging", ".", "error", "(", "\"Processed rewards are not discrete, `num_rewards` returning None\"", ")", "return", "None", "min_reward", ",", "max_reward", "=", "self", ".", "reward_range", "return", "max_reward", "-", "min_reward", "+", "1" ]
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: np.ndarray of stacked observations from the reset-ed envs. """ # 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 dimensionality of the observation. return np.stack([self._envs[index].reset() for index in indices])
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: np.ndarray of stacked observations from the reset-ed envs. """ # 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 dimensionality of the observation. return np.stack([self._envs[index].reset() for index in indices])
[ "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 dimensionality of the observation.", "return", "np", ".", "stack", "(", "[", "self", ".", "_envs", "[", "index", "]", ".", "reset", "(", ")", "for", "index", "in", "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: np.ndarray of stacked observations from the reset-ed envs.
[ "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. Returns: a tuple of stacked raw observations, raw rewards, dones and infos. """ # Pre-conditions: common_preconditions, see `assert_common_preconditions`. # : len(actions) == len(self._envs) self.assert_common_preconditions() assert len(actions) == len(self._envs) observations = [] rewards = [] dones = [] infos = [] # Take steps in all environments. for env, action in zip(self._envs, actions): observation, reward, done, info = env.step(action) observations.append(observation) rewards.append(reward) dones.append(done) infos.append(info) # Convert each list (observations, rewards, ...) into np.array and return a # tuple. return tuple(map(np.stack, [observations, rewards, dones, infos]))
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. Returns: a tuple of stacked raw observations, raw rewards, dones and infos. """ # Pre-conditions: common_preconditions, see `assert_common_preconditions`. # : len(actions) == len(self._envs) self.assert_common_preconditions() assert len(actions) == len(self._envs) observations = [] rewards = [] dones = [] infos = [] # Take steps in all environments. for env, action in zip(self._envs, actions): observation, reward, done, info = env.step(action) observations.append(observation) rewards.append(reward) dones.append(done) infos.append(info) # Convert each list (observations, rewards, ...) into np.array and return a # tuple. return tuple(map(np.stack, [observations, rewards, dones, infos]))
[ "def", "_step", "(", "self", ",", "actions", ")", ":", "# Pre-conditions: common_preconditions, see `assert_common_preconditions`.", "# : len(actions) == len(self._envs)", "self", ".", "assert_common_preconditions", "(", ")", "assert", "len", "(", "actions", ")", "==", "len", "(", "self", ".", "_envs", ")", "observations", "=", "[", "]", "rewards", "=", "[", "]", "dones", "=", "[", "]", "infos", "=", "[", "]", "# Take steps in all environments.", "for", "env", ",", "action", "in", "zip", "(", "self", ".", "_envs", ",", "actions", ")", ":", "observation", ",", "reward", ",", "done", ",", "info", "=", "env", ".", "step", "(", "action", ")", "observations", ".", "append", "(", "observation", ")", "rewards", ".", "append", "(", "reward", ")", "dones", ".", "append", "(", "done", ")", "infos", ".", "append", "(", "info", ")", "# Convert each list (observations, rewards, ...) into np.array and return a", "# tuple.", "return", "tuple", "(", "map", "(", "np", ".", "stack", ",", "[", "observations", ",", "rewards", ",", "dones", ",", "infos", "]", ")", ")" ]
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 observations, raw rewards, dones and infos.
[ "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). """ observations, raw_rewards, dones, infos = self._step(actions) # Process rewards. raw_rewards = raw_rewards.astype(np.float32) processed_rewards = self.process_rewards(raw_rewards) # Process observations. processed_observations = self.process_observations(observations) # Record history. self.trajectories.step(processed_observations, raw_rewards, processed_rewards, dones, actions) return processed_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). """ observations, raw_rewards, dones, infos = self._step(actions) # Process rewards. raw_rewards = raw_rewards.astype(np.float32) processed_rewards = self.process_rewards(raw_rewards) # Process observations. processed_observations = self.process_observations(observations) # Record history. self.trajectories.step(processed_observations, raw_rewards, processed_rewards, dones, actions) return processed_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", ".", "float32", ")", "processed_rewards", "=", "self", ".", "process_rewards", "(", "raw_rewards", ")", "# Process observations.", "processed_observations", "=", "self", ".", "process_observations", "(", "observations", ")", "# Record history.", "self", ".", "trajectories", ".", "step", "(", "processed_observations", ",", "raw_rewards", ",", "processed_rewards", ",", "dones", ",", "actions", ")", "return", "processed_observations", ",", "processed_rewards", ",", "dones", ",", "infos" ]
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.FixedLenFeature((1,), tf.int64), RAW_REWARD_FIELD: tf.FixedLenFeature((1,), tf.float32), PROCESSED_REWARD_FIELD: tf.FixedLenFeature((1,), processed_reward_type), DONE_FIELD: tf.FixedLenFeature((1,), tf.int64), # we wrote this as int. # Special treatment because we need to determine type and shape, also # enables classes to override. OBSERVATION_FIELD: self.observation_spec, ACTION_FIELD: self.action_spec, } data_items_to_decoders = { field: tf.contrib.slim.tfexample_decoder.Tensor(field) for field in data_fields } return data_fields, data_items_to_decoders
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.FixedLenFeature((1,), tf.int64), RAW_REWARD_FIELD: tf.FixedLenFeature((1,), tf.float32), PROCESSED_REWARD_FIELD: tf.FixedLenFeature((1,), processed_reward_type), DONE_FIELD: tf.FixedLenFeature((1,), tf.int64), # we wrote this as int. # Special treatment because we need to determine type and shape, also # enables classes to override. OBSERVATION_FIELD: self.observation_spec, ACTION_FIELD: self.action_spec, } data_items_to_decoders = { field: tf.contrib.slim.tfexample_decoder.Tensor(field) for field in data_fields } return data_fields, data_items_to_decoders
[ "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", "=", "{", "TIMESTEP_FIELD", ":", "tf", ".", "FixedLenFeature", "(", "(", "1", ",", ")", ",", "tf", ".", "int64", ")", ",", "RAW_REWARD_FIELD", ":", "tf", ".", "FixedLenFeature", "(", "(", "1", ",", ")", ",", "tf", ".", "float32", ")", ",", "PROCESSED_REWARD_FIELD", ":", "tf", ".", "FixedLenFeature", "(", "(", "1", ",", ")", ",", "processed_reward_type", ")", ",", "DONE_FIELD", ":", "tf", ".", "FixedLenFeature", "(", "(", "1", ",", ")", ",", "tf", ".", "int64", ")", ",", "# we wrote this as int.", "# Special treatment because we need to determine type and shape, also", "# enables classes to override.", "OBSERVATION_FIELD", ":", "self", ".", "observation_spec", ",", "ACTION_FIELD", ":", "self", ".", "action_spec", ",", "}", "data_items_to_decoders", "=", "{", "field", ":", "tf", ".", "contrib", ".", "slim", ".", "tfexample_decoder", ".", "Tensor", "(", "field", ")", "for", "field", "in", "data_fields", "}", "return", "data_fields", ",", "data_items_to_decoders" ]
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 # could just be a repeated reset. if single_trajectory.num_time_steps <= 1: continue for index, time_step in enumerate(single_trajectory.time_steps): # The first time-step doesn't have reward/processed_reward, if so, just # setting it to 0.0 / 0 should be OK. raw_reward = time_step.raw_reward if not raw_reward: raw_reward = 0.0 processed_reward = time_step.processed_reward if not processed_reward: processed_reward = 0 action = time_step.action if action is None: # The last time-step doesn't have action, and this action shouldn't be # used, gym's spaces have a `sample` function, so let's just sample an # action and use that. action = self.action_space.sample() action = gym_spaces_utils.gym_space_encode(self.action_space, action) if six.PY3: # py3 complains that, to_example cannot handle np.int64 ! action_dtype = self.action_space.dtype if action_dtype in [np.int64, np.int32]: action = list(map(int, action)) elif action_dtype in [np.float64, np.float32]: action = list(map(float, action)) # same with processed_reward. processed_reward = int(processed_reward) assert time_step.observation is not None yield { TIMESTEP_FIELD: [index], ACTION_FIELD: action, # to_example errors on np.float32 RAW_REWARD_FIELD: [float(raw_reward)], PROCESSED_REWARD_FIELD: [processed_reward], # to_example doesn't know bools DONE_FIELD: [int(time_step.done)], OBSERVATION_FIELD: gym_spaces_utils.gym_space_encode(self.observation_space, time_step.observation), }
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 # could just be a repeated reset. if single_trajectory.num_time_steps <= 1: continue for index, time_step in enumerate(single_trajectory.time_steps): # The first time-step doesn't have reward/processed_reward, if so, just # setting it to 0.0 / 0 should be OK. raw_reward = time_step.raw_reward if not raw_reward: raw_reward = 0.0 processed_reward = time_step.processed_reward if not processed_reward: processed_reward = 0 action = time_step.action if action is None: # The last time-step doesn't have action, and this action shouldn't be # used, gym's spaces have a `sample` function, so let's just sample an # action and use that. action = self.action_space.sample() action = gym_spaces_utils.gym_space_encode(self.action_space, action) if six.PY3: # py3 complains that, to_example cannot handle np.int64 ! action_dtype = self.action_space.dtype if action_dtype in [np.int64, np.int32]: action = list(map(int, action)) elif action_dtype in [np.float64, np.float32]: action = list(map(float, action)) # same with processed_reward. processed_reward = int(processed_reward) assert time_step.observation is not None yield { TIMESTEP_FIELD: [index], ACTION_FIELD: action, # to_example errors on np.float32 RAW_REWARD_FIELD: [float(raw_reward)], PROCESSED_REWARD_FIELD: [processed_reward], # to_example doesn't know bools DONE_FIELD: [int(time_step.done)], OBSERVATION_FIELD: gym_spaces_utils.gym_space_encode(self.observation_space, time_step.observation), }
[ "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 single time-step -- this", "# could just be a repeated reset.", "if", "single_trajectory", ".", "num_time_steps", "<=", "1", ":", "continue", "for", "index", ",", "time_step", "in", "enumerate", "(", "single_trajectory", ".", "time_steps", ")", ":", "# The first time-step doesn't have reward/processed_reward, if so, just", "# setting it to 0.0 / 0 should be OK.", "raw_reward", "=", "time_step", ".", "raw_reward", "if", "not", "raw_reward", ":", "raw_reward", "=", "0.0", "processed_reward", "=", "time_step", ".", "processed_reward", "if", "not", "processed_reward", ":", "processed_reward", "=", "0", "action", "=", "time_step", ".", "action", "if", "action", "is", "None", ":", "# The last time-step doesn't have action, and this action shouldn't be", "# used, gym's spaces have a `sample` function, so let's just sample an", "# action and use that.", "action", "=", "self", ".", "action_space", ".", "sample", "(", ")", "action", "=", "gym_spaces_utils", ".", "gym_space_encode", "(", "self", ".", "action_space", ",", "action", ")", "if", "six", ".", "PY3", ":", "# py3 complains that, to_example cannot handle np.int64 !", "action_dtype", "=", "self", ".", "action_space", ".", "dtype", "if", "action_dtype", "in", "[", "np", ".", "int64", ",", "np", ".", "int32", "]", ":", "action", "=", "list", "(", "map", "(", "int", ",", "action", ")", ")", "elif", "action_dtype", "in", "[", "np", ".", "float64", ",", "np", ".", "float32", "]", ":", "action", "=", "list", "(", "map", "(", "float", ",", "action", ")", ")", "# same with processed_reward.", "processed_reward", "=", "int", "(", "processed_reward", ")", "assert", "time_step", ".", "observation", "is", "not", "None", "yield", "{", "TIMESTEP_FIELD", ":", "[", "index", "]", ",", "ACTION_FIELD", ":", "action", ",", "# to_example errors on np.float32", "RAW_REWARD_FIELD", ":", "[", "float", "(", "raw_reward", ")", "]", ",", "PROCESSED_REWARD_FIELD", ":", "[", "processed_reward", "]", ",", "# to_example doesn't know bools", "DONE_FIELD", ":", "[", "int", "(", "time_step", ".", "done", ")", "]", ",", "OBSERVATION_FIELD", ":", "gym_spaces_utils", ".", "gym_space_encode", "(", "self", ".", "observation_space", ",", "time_step", ".", "observation", ")", ",", "}" ]
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)], first_relu=first_relu, name="decompress_conv") return tf.reshape(thicker, [shape[0], shape[1] * 2, 1, hparams.hidden_size])
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)], first_relu=first_relu, name="decompress_conv") return tf.reshape(thicker, [shape[0], shape[1] * 2, 1, hparams.hidden_size])
[ "def", "decompress_step", "(", "source", ",", "hparams", ",", "first_relu", ",", "name", ")", ":", "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", ")", "]", ",", "first_relu", "=", "first_relu", ",", "name", "=", "\"decompress_conv\"", ")", "return", "tf", ".", "reshape", "(", "thicker", ",", "[", "shape", "[", "0", "]", ",", "shape", "[", "1", "]", "*", "2", ",", "1", ",", "hparams", ".", "hidden_size", "]", ")" ]
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 transformer.transformer_encoder( encoder_input, encoder_self_attention_bias, hparams), ed
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 transformer.transformer_encoder( encoder_input, encoder_self_attention_bias, hparams), ed
[ "def", "encode", "(", "x", ",", "x_space", ",", "hparams", ",", "name", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "ed", ")", "=", "transformer", ".", "transformer_prepare_encoder", "(", "x", ",", "x_space", ",", "hparams", ")", "encoder_input", "=", "tf", ".", "nn", ".", "dropout", "(", "encoder_input", ",", "1.0", "-", "hparams", ".", "dropout", ")", "return", "transformer", ".", "transformer_encoder", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "hparams", ")", ",", "ed" ]
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 = [] # NOTE: The LogSoftmax instead of the Softmax. bottom_layers.extend([layers.Dense(num_actions), layers.LogSoftmax()]) net = layers.Serial(*bottom_layers) return net.initialize(batch_observations_shape, rng_key), net
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 = [] # NOTE: The LogSoftmax instead of the Softmax. bottom_layers.extend([layers.Dense(num_actions), layers.LogSoftmax()]) net = layers.Serial(*bottom_layers) return net.initialize(batch_observations_shape, rng_key), net
[ "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", "None", ":", "bottom_layers", "=", "[", "]", "# NOTE: The LogSoftmax instead of the Softmax.", "bottom_layers", ".", "extend", "(", "[", "layers", ".", "Dense", "(", "num_actions", ")", ",", "layers", ".", "LogSoftmax", "(", ")", "]", ")", "net", "=", "layers", ".", "Serial", "(", "*", "bottom_layers", ")", "return", "net", ".", "initialize", "(", "batch_observations_shape", ",", "rng_key", ")", ",", "net" ]
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) return net.initialize(batch_observations_shape, rng_key), net
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) return net.initialize(batch_observations_shape, rng_key), net
[ "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", "(", "[", "layers", ".", "Dense", "(", "1", ")", ",", "]", ")", "net", "=", "layers", ".", "Serial", "(", "*", "bottom_layers", ")", "return", "net", ".", "initialize", "(", "batch_observations_shape", ",", "rng_key", ")", ",", "net" ]
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, with the current logits, one head computes action probabilities and the # other computes the value function. # NOTE: The LogSoftmax instead of the Softmax because of numerical stability. cur_layers.extend([layers.Branch(), layers.Parallel( layers.Serial(layers.Dense(num_actions), layers.LogSoftmax()), layers.Dense(1) )]) net = layers.Serial(*cur_layers) return net.initialize(batch_observations_shape, rng_key), net
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, with the current logits, one head computes action probabilities and the # other computes the value function. # NOTE: The LogSoftmax instead of the Softmax because of numerical stability. cur_layers.extend([layers.Branch(), layers.Parallel( layers.Serial(layers.Dense(num_actions), layers.LogSoftmax()), layers.Dense(1) )]) net = layers.Serial(*cur_layers) return net.initialize(batch_observations_shape, rng_key), net
[ "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", "(", "bottom_layers", ")", "# Now, with the current logits, one head computes action probabilities and the", "# other computes the value function.", "# NOTE: The LogSoftmax instead of the Softmax because of numerical stability.", "cur_layers", ".", "extend", "(", "[", "layers", ".", "Branch", "(", ")", ",", "layers", ".", "Parallel", "(", "layers", ".", "Serial", "(", "layers", ".", "Dense", "(", "num_actions", ")", ",", "layers", ".", "LogSoftmax", "(", ")", ")", ",", "layers", ".", "Dense", "(", "1", ")", ")", "]", ")", "net", "=", "layers", ".", "Serial", "(", "*", "cur_layers", ")", "return", "net", ".", "initialize", "(", "batch_observations_shape", ",", "rng_key", ")", ",", "net" ]
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)) else: for j, p in enumerate(param): logging.error( "\t%s[%d, %d] = [%s]", name, i, j, onp.array(p))
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)) else: for j, p in enumerate(param): logging.error( "\t%s[%d, %d] = [%s]", name, i, j, onp.array(p))
[ "def", "log_params", "(", "params", ",", "name", "=", "\"params\"", ")", ":", "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", ")", ")", "else", ":", "for", "j", ",", "p", "in", "enumerate", "(", "param", ")", ":", "logging", ".", "error", "(", "\"\\t%s[%d, %d] = [%s]\"", ",", "name", ",", "i", ",", "j", ",", "onp", ".", "array", "(", "p", ")", ")" ]
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: 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-sampling" i.e. how to use the policy_fun to return an action. max_timestep: int or None, the index of the maximum time-step at which we return the trajectory, None for ending a trajectory only when env returns done. epsilon: float, the epsilon for `epsilon-greedy` policy. Returns: trajectory: list of (observation, action, reward) tuples, where each element `i` is a tuple of numpy arrays with shapes as follows: observation[i] = (B, T_i + 1) action[i] = (B, T_i) reward[i] = (B, T_i) """ trajectories = [] for t in range(num_trajectories): t_start = time.time() rewards = [] actions = [] done = False observation = env.reset() # This is currently shaped (1, 1) + OBS, but new observations will keep # getting added to it, making it eventually (1, T+1) + OBS observation_history = observation[np.newaxis, np.newaxis, :] # Run either till we're done OR if max_timestep is defined only till that # timestep. ts = 0 while ((not done) and (not max_timestep or observation_history.shape[1] < max_timestep)): ts_start = time.time() # Run the policy, to pick an action, shape is (1, t, A) because # observation_history is shaped (1, t) + OBS predictions = policy_fun(observation_history) # We need the predictions for the last time-step, so squeeze the batch # dimension and take the last time-step. predictions = np.squeeze(predictions, axis=0)[-1] # Policy can be run in one of the following ways: # - Greedy # - Epsilon-Greedy # - Categorical-Sampling action = None if policy == "greedy": action = np.argmax(predictions) elif policy == "epsilon-greedy": # A schedule for epsilon is 1/k where k is the episode number sampled. if onp.random.random() < epsilon: # Choose an action at random. action = onp.random.randint(0, high=len(predictions)) else: # Return the best action. action = np.argmax(predictions) elif policy == "categorical-sampling": # NOTE: The predictions aren't probabilities but log-probabilities # instead, since they were computed with LogSoftmax. # So just np.exp them to make them probabilities. predictions = np.exp(predictions) action = onp.argwhere(onp.random.multinomial(1, predictions) == 1) else: raise ValueError("Unknown policy: %s" % policy) # NOTE: Assumption, single batch. try: action = int(action) except TypeError as err: # Let's dump some information before we die off. logging.error("Cannot convert action into an integer: [%s]", err) logging.error("action.shape: [%s]", action.shape) logging.error("action: [%s]", action) logging.error("predictions.shape: [%s]", predictions.shape) logging.error("predictions: [%s]", predictions) logging.error("observation_history: [%s]", observation_history) raise err observation, reward, done, _ = env.step(action) # observation is of shape OBS, so add extra dims and concatenate on the # time dimension. observation_history = np.concatenate( [observation_history, observation[np.newaxis, np.newaxis, :]], axis=1) rewards.append(reward) actions.append(action) ts += 1 logging.vlog( 2, " Collected time-step[ %5d] of trajectory[ %5d] in [%0.2f] msec.", ts, t, get_time(ts_start)) logging.vlog( 2, " Collected trajectory[ %5d] in [%0.2f] msec.", t, get_time(t_start)) # This means we are done we're been terminated early. assert done or ( max_timestep and max_timestep >= observation_history.shape[1]) # observation_history is (1, T+1) + OBS, lets squeeze out the batch dim. observation_history = np.squeeze(observation_history, axis=0) trajectories.append( (observation_history, np.stack(actions), np.stack(rewards))) return trajectories
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: 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-sampling" i.e. how to use the policy_fun to return an action. max_timestep: int or None, the index of the maximum time-step at which we return the trajectory, None for ending a trajectory only when env returns done. epsilon: float, the epsilon for `epsilon-greedy` policy. Returns: trajectory: list of (observation, action, reward) tuples, where each element `i` is a tuple of numpy arrays with shapes as follows: observation[i] = (B, T_i + 1) action[i] = (B, T_i) reward[i] = (B, T_i) """ trajectories = [] for t in range(num_trajectories): t_start = time.time() rewards = [] actions = [] done = False observation = env.reset() # This is currently shaped (1, 1) + OBS, but new observations will keep # getting added to it, making it eventually (1, T+1) + OBS observation_history = observation[np.newaxis, np.newaxis, :] # Run either till we're done OR if max_timestep is defined only till that # timestep. ts = 0 while ((not done) and (not max_timestep or observation_history.shape[1] < max_timestep)): ts_start = time.time() # Run the policy, to pick an action, shape is (1, t, A) because # observation_history is shaped (1, t) + OBS predictions = policy_fun(observation_history) # We need the predictions for the last time-step, so squeeze the batch # dimension and take the last time-step. predictions = np.squeeze(predictions, axis=0)[-1] # Policy can be run in one of the following ways: # - Greedy # - Epsilon-Greedy # - Categorical-Sampling action = None if policy == "greedy": action = np.argmax(predictions) elif policy == "epsilon-greedy": # A schedule for epsilon is 1/k where k is the episode number sampled. if onp.random.random() < epsilon: # Choose an action at random. action = onp.random.randint(0, high=len(predictions)) else: # Return the best action. action = np.argmax(predictions) elif policy == "categorical-sampling": # NOTE: The predictions aren't probabilities but log-probabilities # instead, since they were computed with LogSoftmax. # So just np.exp them to make them probabilities. predictions = np.exp(predictions) action = onp.argwhere(onp.random.multinomial(1, predictions) == 1) else: raise ValueError("Unknown policy: %s" % policy) # NOTE: Assumption, single batch. try: action = int(action) except TypeError as err: # Let's dump some information before we die off. logging.error("Cannot convert action into an integer: [%s]", err) logging.error("action.shape: [%s]", action.shape) logging.error("action: [%s]", action) logging.error("predictions.shape: [%s]", predictions.shape) logging.error("predictions: [%s]", predictions) logging.error("observation_history: [%s]", observation_history) raise err observation, reward, done, _ = env.step(action) # observation is of shape OBS, so add extra dims and concatenate on the # time dimension. observation_history = np.concatenate( [observation_history, observation[np.newaxis, np.newaxis, :]], axis=1) rewards.append(reward) actions.append(action) ts += 1 logging.vlog( 2, " Collected time-step[ %5d] of trajectory[ %5d] in [%0.2f] msec.", ts, t, get_time(ts_start)) logging.vlog( 2, " Collected trajectory[ %5d] in [%0.2f] msec.", t, get_time(t_start)) # This means we are done we're been terminated early. assert done or ( max_timestep and max_timestep >= observation_history.shape[1]) # observation_history is (1, T+1) + OBS, lets squeeze out the batch dim. observation_history = np.squeeze(observation_history, axis=0) trajectories.append( (observation_history, np.stack(actions), np.stack(rewards))) return trajectories
[ "def", "collect_trajectories", "(", "env", ",", "policy_fun", ",", "num_trajectories", "=", "1", ",", "policy", "=", "\"greedy\"", ",", "max_timestep", "=", "None", ",", "epsilon", "=", "0.1", ")", ":", "trajectories", "=", "[", "]", "for", "t", "in", "range", "(", "num_trajectories", ")", ":", "t_start", "=", "time", ".", "time", "(", ")", "rewards", "=", "[", "]", "actions", "=", "[", "]", "done", "=", "False", "observation", "=", "env", ".", "reset", "(", ")", "# This is currently shaped (1, 1) + OBS, but new observations will keep", "# getting added to it, making it eventually (1, T+1) + OBS", "observation_history", "=", "observation", "[", "np", ".", "newaxis", ",", "np", ".", "newaxis", ",", ":", "]", "# Run either till we're done OR if max_timestep is defined only till that", "# timestep.", "ts", "=", "0", "while", "(", "(", "not", "done", ")", "and", "(", "not", "max_timestep", "or", "observation_history", ".", "shape", "[", "1", "]", "<", "max_timestep", ")", ")", ":", "ts_start", "=", "time", ".", "time", "(", ")", "# Run the policy, to pick an action, shape is (1, t, A) because", "# observation_history is shaped (1, t) + OBS", "predictions", "=", "policy_fun", "(", "observation_history", ")", "# We need the predictions for the last time-step, so squeeze the batch", "# dimension and take the last time-step.", "predictions", "=", "np", ".", "squeeze", "(", "predictions", ",", "axis", "=", "0", ")", "[", "-", "1", "]", "# Policy can be run in one of the following ways:", "# - Greedy", "# - Epsilon-Greedy", "# - Categorical-Sampling", "action", "=", "None", "if", "policy", "==", "\"greedy\"", ":", "action", "=", "np", ".", "argmax", "(", "predictions", ")", "elif", "policy", "==", "\"epsilon-greedy\"", ":", "# A schedule for epsilon is 1/k where k is the episode number sampled.", "if", "onp", ".", "random", ".", "random", "(", ")", "<", "epsilon", ":", "# Choose an action at random.", "action", "=", "onp", ".", "random", ".", "randint", "(", "0", ",", "high", "=", "len", "(", "predictions", ")", ")", "else", ":", "# Return the best action.", "action", "=", "np", ".", "argmax", "(", "predictions", ")", "elif", "policy", "==", "\"categorical-sampling\"", ":", "# NOTE: The predictions aren't probabilities but log-probabilities", "# instead, since they were computed with LogSoftmax.", "# So just np.exp them to make them probabilities.", "predictions", "=", "np", ".", "exp", "(", "predictions", ")", "action", "=", "onp", ".", "argwhere", "(", "onp", ".", "random", ".", "multinomial", "(", "1", ",", "predictions", ")", "==", "1", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown policy: %s\"", "%", "policy", ")", "# NOTE: Assumption, single batch.", "try", ":", "action", "=", "int", "(", "action", ")", "except", "TypeError", "as", "err", ":", "# Let's dump some information before we die off.", "logging", ".", "error", "(", "\"Cannot convert action into an integer: [%s]\"", ",", "err", ")", "logging", ".", "error", "(", "\"action.shape: [%s]\"", ",", "action", ".", "shape", ")", "logging", ".", "error", "(", "\"action: [%s]\"", ",", "action", ")", "logging", ".", "error", "(", "\"predictions.shape: [%s]\"", ",", "predictions", ".", "shape", ")", "logging", ".", "error", "(", "\"predictions: [%s]\"", ",", "predictions", ")", "logging", ".", "error", "(", "\"observation_history: [%s]\"", ",", "observation_history", ")", "raise", "err", "observation", ",", "reward", ",", "done", ",", "_", "=", "env", ".", "step", "(", "action", ")", "# observation is of shape OBS, so add extra dims and concatenate on the", "# time dimension.", "observation_history", "=", "np", ".", "concatenate", "(", "[", "observation_history", ",", "observation", "[", "np", ".", "newaxis", ",", "np", ".", "newaxis", ",", ":", "]", "]", ",", "axis", "=", "1", ")", "rewards", ".", "append", "(", "reward", ")", "actions", ".", "append", "(", "action", ")", "ts", "+=", "1", "logging", ".", "vlog", "(", "2", ",", "\" Collected time-step[ %5d] of trajectory[ %5d] in [%0.2f] msec.\"", ",", "ts", ",", "t", ",", "get_time", "(", "ts_start", ")", ")", "logging", ".", "vlog", "(", "2", ",", "\" Collected trajectory[ %5d] in [%0.2f] msec.\"", ",", "t", ",", "get_time", "(", "t_start", ")", ")", "# This means we are done we're been terminated early.", "assert", "done", "or", "(", "max_timestep", "and", "max_timestep", ">=", "observation_history", ".", "shape", "[", "1", "]", ")", "# observation_history is (1, T+1) + OBS, lets squeeze out the batch dim.", "observation_history", "=", "np", ".", "squeeze", "(", "observation_history", ",", "axis", "=", "0", ")", "trajectories", ".", "append", "(", "(", "observation_history", ",", "np", ".", "stack", "(", "actions", ")", ",", "np", ".", "stack", "(", "rewards", ")", ")", ")", "return", "trajectories" ]
Collect trajectories with the given policy net and behaviour. Args: env: A gym env interface, for now this is not-batched. policy_fun: observations(B,T+1) -> log-probabs(B,T+1, A) callable. num_trajectories: int, number of trajectories. policy: string, "greedy", "epsilon-greedy", or "categorical-sampling" i.e. how to use the policy_fun to return an action. max_timestep: int or None, the index of the maximum time-step at which we return the trajectory, None for ending a trajectory only when env returns done. epsilon: float, the epsilon for `epsilon-greedy` policy. Returns: trajectory: list of (observation, action, reward) tuples, where each element `i` is a tuple of numpy arrays with shapes as follows: observation[i] = (B, T_i + 1) action[i] = (B, T_i) reward[i] = (B, T_i)
[ "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_value is not None return padding_value
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_value is not None return padding_value
[ "def", "get_padding_value", "(", "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_value", "is", "not", "None", "return", "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 (batch size). boundary: int, bucket length, the actions and rewards are padded to integer multiples of boundary. Returns: tuple: (padding lengths, reward_mask, padded_observations, padded_actions, padded_rewards) where padded_observations is shaped (B, T+1) + OBS and padded_actions, padded_rewards & reward_mask are shaped (B, T). Where T is max(t) rounded up to an integer multiple of boundary. padded_length is how much padding we've added and reward_mask is 1s for actual rewards and 0s for the padding. """ # Let's compute max(t) over all trajectories. t_max = max(r.shape[0] for (_, _, r) in trajectories) # t_max is rounded to the next multiple of `boundary` boundary = int(boundary) bucket_length = boundary * int(np.ceil(float(t_max) / boundary)) # So all obs will be padded to t_max + 1 and actions and rewards to t_max. padded_observations = [] padded_actions = [] padded_rewards = [] padded_lengths = [] reward_masks = [] for (o, a, r) in trajectories: # Determine the amount to pad, this holds true for obs, actions and rewards. num_to_pad = bucket_length + 1 - o.shape[0] padded_lengths.append(num_to_pad) if num_to_pad == 0: padded_observations.append(o) padded_actions.append(a) padded_rewards.append(r) reward_masks.append(onp.ones_like(r, dtype=np.int32)) continue # First pad observations. padding_config = [(0, num_to_pad, 0)] for _ in range(o.ndim - 1): padding_config.append((0, 0, 0)) padding_config = tuple(padding_config) padding_value = get_padding_value(o.dtype) action_padding_value = get_padding_value(a.dtype) reward_padding_value = get_padding_value(r.dtype) padded_obs = lax.pad(o, padding_value, padding_config) padded_observations.append(padded_obs) # Now pad actions and rewards. assert a.ndim == 1 and r.ndim == 1 padding_config = ((0, num_to_pad, 0),) padded_action = lax.pad(a, action_padding_value, padding_config) padded_actions.append(padded_action) padded_reward = lax.pad(r, reward_padding_value, padding_config) padded_rewards.append(padded_reward) # Also create the mask to use later. reward_mask = onp.ones_like(r, dtype=np.int32) reward_masks.append(lax.pad(reward_mask, 0, padding_config)) return padded_lengths, np.stack(reward_masks), np.stack( padded_observations), np.stack(padded_actions), np.stack(padded_rewards)
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 (batch size). boundary: int, bucket length, the actions and rewards are padded to integer multiples of boundary. Returns: tuple: (padding lengths, reward_mask, padded_observations, padded_actions, padded_rewards) where padded_observations is shaped (B, T+1) + OBS and padded_actions, padded_rewards & reward_mask are shaped (B, T). Where T is max(t) rounded up to an integer multiple of boundary. padded_length is how much padding we've added and reward_mask is 1s for actual rewards and 0s for the padding. """ # Let's compute max(t) over all trajectories. t_max = max(r.shape[0] for (_, _, r) in trajectories) # t_max is rounded to the next multiple of `boundary` boundary = int(boundary) bucket_length = boundary * int(np.ceil(float(t_max) / boundary)) # So all obs will be padded to t_max + 1 and actions and rewards to t_max. padded_observations = [] padded_actions = [] padded_rewards = [] padded_lengths = [] reward_masks = [] for (o, a, r) in trajectories: # Determine the amount to pad, this holds true for obs, actions and rewards. num_to_pad = bucket_length + 1 - o.shape[0] padded_lengths.append(num_to_pad) if num_to_pad == 0: padded_observations.append(o) padded_actions.append(a) padded_rewards.append(r) reward_masks.append(onp.ones_like(r, dtype=np.int32)) continue # First pad observations. padding_config = [(0, num_to_pad, 0)] for _ in range(o.ndim - 1): padding_config.append((0, 0, 0)) padding_config = tuple(padding_config) padding_value = get_padding_value(o.dtype) action_padding_value = get_padding_value(a.dtype) reward_padding_value = get_padding_value(r.dtype) padded_obs = lax.pad(o, padding_value, padding_config) padded_observations.append(padded_obs) # Now pad actions and rewards. assert a.ndim == 1 and r.ndim == 1 padding_config = ((0, num_to_pad, 0),) padded_action = lax.pad(a, action_padding_value, padding_config) padded_actions.append(padded_action) padded_reward = lax.pad(r, reward_padding_value, padding_config) padded_rewards.append(padded_reward) # Also create the mask to use later. reward_mask = onp.ones_like(r, dtype=np.int32) reward_masks.append(lax.pad(reward_mask, 0, padding_config)) return padded_lengths, np.stack(reward_masks), np.stack( padded_observations), np.stack(padded_actions), np.stack(padded_rewards)
[ "def", "pad_trajectories", "(", "trajectories", ",", "boundary", "=", "20", ")", ":", "# Let's compute max(t) over all trajectories.", "t_max", "=", "max", "(", "r", ".", "shape", "[", "0", "]", "for", "(", "_", ",", "_", ",", "r", ")", "in", "trajectories", ")", "# t_max is rounded to the next multiple of `boundary`", "boundary", "=", "int", "(", "boundary", ")", "bucket_length", "=", "boundary", "*", "int", "(", "np", ".", "ceil", "(", "float", "(", "t_max", ")", "/", "boundary", ")", ")", "# So all obs will be padded to t_max + 1 and actions and rewards to t_max.", "padded_observations", "=", "[", "]", "padded_actions", "=", "[", "]", "padded_rewards", "=", "[", "]", "padded_lengths", "=", "[", "]", "reward_masks", "=", "[", "]", "for", "(", "o", ",", "a", ",", "r", ")", "in", "trajectories", ":", "# Determine the amount to pad, this holds true for obs, actions and rewards.", "num_to_pad", "=", "bucket_length", "+", "1", "-", "o", ".", "shape", "[", "0", "]", "padded_lengths", ".", "append", "(", "num_to_pad", ")", "if", "num_to_pad", "==", "0", ":", "padded_observations", ".", "append", "(", "o", ")", "padded_actions", ".", "append", "(", "a", ")", "padded_rewards", ".", "append", "(", "r", ")", "reward_masks", ".", "append", "(", "onp", ".", "ones_like", "(", "r", ",", "dtype", "=", "np", ".", "int32", ")", ")", "continue", "# First pad observations.", "padding_config", "=", "[", "(", "0", ",", "num_to_pad", ",", "0", ")", "]", "for", "_", "in", "range", "(", "o", ".", "ndim", "-", "1", ")", ":", "padding_config", ".", "append", "(", "(", "0", ",", "0", ",", "0", ")", ")", "padding_config", "=", "tuple", "(", "padding_config", ")", "padding_value", "=", "get_padding_value", "(", "o", ".", "dtype", ")", "action_padding_value", "=", "get_padding_value", "(", "a", ".", "dtype", ")", "reward_padding_value", "=", "get_padding_value", "(", "r", ".", "dtype", ")", "padded_obs", "=", "lax", ".", "pad", "(", "o", ",", "padding_value", ",", "padding_config", ")", "padded_observations", ".", "append", "(", "padded_obs", ")", "# Now pad actions and rewards.", "assert", "a", ".", "ndim", "==", "1", "and", "r", ".", "ndim", "==", "1", "padding_config", "=", "(", "(", "0", ",", "num_to_pad", ",", "0", ")", ",", ")", "padded_action", "=", "lax", ".", "pad", "(", "a", ",", "action_padding_value", ",", "padding_config", ")", "padded_actions", ".", "append", "(", "padded_action", ")", "padded_reward", "=", "lax", ".", "pad", "(", "r", ",", "reward_padding_value", ",", "padding_config", ")", "padded_rewards", ".", "append", "(", "padded_reward", ")", "# Also create the mask to use later.", "reward_mask", "=", "onp", ".", "ones_like", "(", "r", ",", "dtype", "=", "np", ".", "int32", ")", "reward_masks", ".", "append", "(", "lax", ".", "pad", "(", "reward_mask", ",", "0", ",", "padding_config", ")", ")", "return", "padded_lengths", ",", "np", ".", "stack", "(", "reward_masks", ")", ",", "np", ".", "stack", "(", "padded_observations", ")", ",", "np", ".", "stack", "(", "padded_actions", ")", ",", "np", ".", "stack", "(", "padded_rewards", ")" ]
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 actions and rewards are padded to integer multiples of boundary. Returns: tuple: (padding lengths, reward_mask, padded_observations, padded_actions, padded_rewards) where padded_observations is shaped (B, T+1) + OBS and padded_actions, padded_rewards & reward_mask are shaped (B, T). Where T is max(t) rounded up to an integer multiple of boundary. padded_length is how much padding we've added and reward_mask is 1s for actual rewards and 0s for the padding.
[ "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 rewards. mask: np.ndarray of shape (B, T) of mask for the rewards. gamma: float, discount factor. Returns: rewards to go, np.ndarray of shape (B, T). """ B, T = rewards.shape # pylint: disable=invalid-name,unused-variable masked_rewards = rewards * mask # (B, T) # We use the following recurrence relation, derived from the equation above: # # r2g[t+1] = (r2g[t] - r[t]) / gamma # # This means we'll need to calculate r2g[0] first and then r2g[1] and so on .. # # **However** this leads to overflows for long sequences: r2g[t] - r[t] > 0 # and gamma < 1.0, so the division keeps increasing. # # So we just run the recurrence in reverse, i.e. # # r2g[t] = r[t] + (gamma*r2g[t+1]) # # This is much better, but might have lost updates since the (small) rewards # at earlier time-steps may get added to a (very?) large sum. # Compute r2g_{T-1} at the start and then compute backwards in time. r2gs = [masked_rewards[:, -1]] # Go from T-2 down to 0. for t in reversed(range(T - 1)): r2gs.append(masked_rewards[:, t] + (gamma * r2gs[-1])) # The list should have length T. assert T == len(r2gs) # First we stack them in the correct way to make it (B, T), but these are # still from newest (T-1) to oldest (0), so then we flip it on time axis. return np.flip(np.stack(r2gs, axis=1), axis=1)
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 rewards. mask: np.ndarray of shape (B, T) of mask for the rewards. gamma: float, discount factor. Returns: rewards to go, np.ndarray of shape (B, T). """ B, T = rewards.shape # pylint: disable=invalid-name,unused-variable masked_rewards = rewards * mask # (B, T) # We use the following recurrence relation, derived from the equation above: # # r2g[t+1] = (r2g[t] - r[t]) / gamma # # This means we'll need to calculate r2g[0] first and then r2g[1] and so on .. # # **However** this leads to overflows for long sequences: r2g[t] - r[t] > 0 # and gamma < 1.0, so the division keeps increasing. # # So we just run the recurrence in reverse, i.e. # # r2g[t] = r[t] + (gamma*r2g[t+1]) # # This is much better, but might have lost updates since the (small) rewards # at earlier time-steps may get added to a (very?) large sum. # Compute r2g_{T-1} at the start and then compute backwards in time. r2gs = [masked_rewards[:, -1]] # Go from T-2 down to 0. for t in reversed(range(T - 1)): r2gs.append(masked_rewards[:, t] + (gamma * r2gs[-1])) # The list should have length T. assert T == len(r2gs) # First we stack them in the correct way to make it (B, T), but these are # still from newest (T-1) to oldest (0), so then we flip it on time axis. return np.flip(np.stack(r2gs, axis=1), axis=1)
[ "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 following recurrence relation, derived from the equation above:", "#", "# r2g[t+1] = (r2g[t] - r[t]) / gamma", "#", "# This means we'll need to calculate r2g[0] first and then r2g[1] and so on ..", "#", "# **However** this leads to overflows for long sequences: r2g[t] - r[t] > 0", "# and gamma < 1.0, so the division keeps increasing.", "#", "# So we just run the recurrence in reverse, i.e.", "#", "# r2g[t] = r[t] + (gamma*r2g[t+1])", "#", "# This is much better, but might have lost updates since the (small) rewards", "# at earlier time-steps may get added to a (very?) large sum.", "# Compute r2g_{T-1} at the start and then compute backwards in time.", "r2gs", "=", "[", "masked_rewards", "[", ":", ",", "-", "1", "]", "]", "# Go from T-2 down to 0.", "for", "t", "in", "reversed", "(", "range", "(", "T", "-", "1", ")", ")", ":", "r2gs", ".", "append", "(", "masked_rewards", "[", ":", ",", "t", "]", "+", "(", "gamma", "*", "r2gs", "[", "-", "1", "]", ")", ")", "# The list should have length T.", "assert", "T", "==", "len", "(", "r2gs", ")", "# First we stack them in the correct way to make it (B, T), but these are", "# still from newest (T-1) to oldest (0), so then we flip it on time axis.", "return", "np", ".", "flip", "(", "np", ".", "stack", "(", "r2gs", ",", "axis", "=", "1", ")", ",", "axis", "=", "1", ")" ]
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 mask for the rewards. gamma: float, discount factor. Returns: rewards to go, np.ndarray of shape (B, T).
[ "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) -> 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. reward_mask: np.ndarray of shape (B, T), the mask over rewards. gamma: float, discount factor. Returns: The average L2 value loss, averaged over instances where reward_mask is 1. """ B, T = rewards.shape # pylint: disable=invalid-name assert (B, T + 1) == observations.shape[:2] # NOTE: observations is (B, T+1) + OBS, value_prediction is (B, T+1, 1) value_prediction = value_net_apply(observations, value_net_params) assert (B, T + 1, 1) == value_prediction.shape return value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma)
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) -> 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. reward_mask: np.ndarray of shape (B, T), the mask over rewards. gamma: float, discount factor. Returns: The average L2 value loss, averaged over instances where reward_mask is 1. """ B, T = rewards.shape # pylint: disable=invalid-name assert (B, T + 1) == observations.shape[:2] # NOTE: observations is (B, T+1) + OBS, value_prediction is (B, T+1, 1) value_prediction = value_net_apply(observations, value_net_params) assert (B, T + 1, 1) == value_prediction.shape return value_loss_given_predictions(value_prediction, rewards, reward_mask, gamma)
[ "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", ",", "T", "+", "1", ")", "==", "observations", ".", "shape", "[", ":", "2", "]", "# NOTE: observations is (B, T+1) + OBS, value_prediction is (B, T+1, 1)", "value_prediction", "=", "value_net_apply", "(", "observations", ",", "value_net_params", ")", "assert", "(", "B", ",", "T", "+", "1", ",", "1", ")", "==", "value_prediction", ".", "shape", "return", "value_loss_given_predictions", "(", "value_prediction", ",", "rewards", ",", "reward_mask", ",", "gamma", ")" ]
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. reward_mask: np.ndarray of shape (B, T), the mask over rewards. gamma: float, discount factor. Returns: The average L2 value loss, averaged over instances where reward_mask is 1.
[ "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) 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 value loss, averaged over instances where reward_mask is 1. """ B, T = rewards.shape # pylint: disable=invalid-name assert (B, T) == reward_mask.shape assert (B, T + 1, 1) == value_prediction.shape value_prediction = np.squeeze(value_prediction, axis=2) # (B, T+1) value_prediction = value_prediction[:, :-1] * reward_mask # (B, T) r2g = rewards_to_go(rewards, reward_mask, gamma=gamma) # (B, T) loss = (value_prediction - r2g)**2 # Take an average on only the points where mask != 0. return np.sum(loss) / np.sum(reward_mask)
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) 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 value loss, averaged over instances where reward_mask is 1. """ B, T = rewards.shape # pylint: disable=invalid-name assert (B, T) == reward_mask.shape assert (B, T + 1, 1) == value_prediction.shape value_prediction = np.squeeze(value_prediction, axis=2) # (B, T+1) value_prediction = value_prediction[:, :-1] * reward_mask # (B, T) r2g = rewards_to_go(rewards, reward_mask, gamma=gamma) # (B, T) loss = (value_prediction - r2g)**2 # Take an average on only the points where mask != 0. return np.sum(loss) / np.sum(reward_mask)
[ "def", "value_loss_given_predictions", "(", "value_prediction", ",", "rewards", ",", "reward_mask", ",", "gamma", "=", "0.99", ")", ":", "B", ",", "T", "=", "rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", ")", "==", "reward_mask", ".", "shape", "assert", "(", "B", ",", "T", "+", "1", ",", "1", ")", "==", "value_prediction", ".", "shape", "value_prediction", "=", "np", ".", "squeeze", "(", "value_prediction", ",", "axis", "=", "2", ")", "# (B, T+1)", "value_prediction", "=", "value_prediction", "[", ":", ",", ":", "-", "1", "]", "*", "reward_mask", "# (B, T)", "r2g", "=", "rewards_to_go", "(", "rewards", ",", "reward_mask", ",", "gamma", "=", "gamma", ")", "# (B, T)", "loss", "=", "(", "value_prediction", "-", "r2g", ")", "**", "2", "# Take an average on only the points where mask != 0.", "return", "np", ".", "sum", "(", "loss", ")", "/", "np", ".", "sum", "(", "reward_mask", ")" ]
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 value loss, averaged over instances where reward_mask is 1.
[ "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 same computation. Args: td_deltas: np.ndarray of shape (B, T) of one step TD-residuals. mask: np.ndarray of shape (B, T) of mask for the residuals. It maybe the case that the `td_deltas` are already masked correctly since they are produced by `deltas(...)` lambda_: float, lambda parameter for GAE estimators. gamma: float, lambda parameter for GAE estimators. Returns: GAE advantage estimates. """ return rewards_to_go(td_deltas, mask, lambda_ * gamma)
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 same computation. Args: td_deltas: np.ndarray of shape (B, T) of one step TD-residuals. mask: np.ndarray of shape (B, T) of mask for the residuals. It maybe the case that the `td_deltas` are already masked correctly since they are produced by `deltas(...)` lambda_: float, lambda parameter for GAE estimators. gamma: float, lambda parameter for GAE estimators. Returns: GAE advantage estimates. """ return rewards_to_go(td_deltas, mask, lambda_ * gamma)
[ "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, T) of one step TD-residuals. mask: np.ndarray of shape (B, T) of mask for the residuals. It maybe the case that the `td_deltas` are already masked correctly since they are produced by `deltas(...)` lambda_: float, lambda parameter for GAE estimators. gamma: float, lambda parameter for GAE estimators. Returns: GAE advantage estimates.
[ "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 trajectory. actions: ndarray of shape `[B, T]`, with each entry in [0, A) denoting which action was chosen in the b^th trajectory's t^th time-step. Returns: `[B, T]` ndarray with the log-probabilities of the chosen actions. """ B, T = actions.shape # pylint: disable=invalid-name assert (B, T + 1) == probab_observations.shape[:2] return probab_observations[np.arange(B)[:, None], np.arange(T), actions]
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 trajectory. actions: ndarray of shape `[B, T]`, with each entry in [0, A) denoting which action was chosen in the b^th trajectory's t^th time-step. Returns: `[B, T]` ndarray with the log-probabilities of the chosen actions. """ B, T = actions.shape # pylint: disable=invalid-name assert (B, T + 1) == probab_observations.shape[:2] return probab_observations[np.arange(B)[:, None], np.arange(T), actions]
[ "def", "chosen_probabs", "(", "probab_observations", ",", "actions", ")", ":", "B", ",", "T", "=", "actions", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "probab_observations", ".", "shape", "[", ":", "2", "]", "return", "probab_observations", "[", "np", ".", "arange", "(", "B", ")", "[", ":", ",", "None", "]", ",", "np", ".", "arange", "(", "T", ")", ",", "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 trajectory. actions: ndarray of shape `[B, T]`, with each entry in [0, A) denoting which action was chosen in the b^th trajectory's t^th time-step. Returns: `[B, T]` ndarray with the log-probabilities of the chosen actions.
[ "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 parameters. p_old: ndarray of shape [B, T+1, A], same as above, but using old policy network parameters. actions: ndarray of shape [B, T] where each element is from [0, A). reward_mask: ndarray of shape [B, T] masking over probabilities. Returns: probab_ratios: ndarray of shape [B, T], where probab_ratios_{b,t} = p_new_{b,t,action_{b,t}} / p_old_{b,t,action_{b,t}} """ B, T = actions.shape # pylint: disable=invalid-name assert (B, T + 1) == p_old.shape[:2] assert (B, T + 1) == p_new.shape[:2] logp_old = chosen_probabs(p_old, actions) logp_new = chosen_probabs(p_new, actions) assert (B, T) == logp_old.shape assert (B, T) == logp_new.shape # Since these are log-probabilities, we just subtract them. probab_ratios = np.exp(logp_new - logp_old) * reward_mask assert (B, T) == probab_ratios.shape return probab_ratios
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 parameters. p_old: ndarray of shape [B, T+1, A], same as above, but using old policy network parameters. actions: ndarray of shape [B, T] where each element is from [0, A). reward_mask: ndarray of shape [B, T] masking over probabilities. Returns: probab_ratios: ndarray of shape [B, T], where probab_ratios_{b,t} = p_new_{b,t,action_{b,t}} / p_old_{b,t,action_{b,t}} """ B, T = actions.shape # pylint: disable=invalid-name assert (B, T + 1) == p_old.shape[:2] assert (B, T + 1) == p_new.shape[:2] logp_old = chosen_probabs(p_old, actions) logp_new = chosen_probabs(p_new, actions) assert (B, T) == logp_old.shape assert (B, T) == logp_new.shape # Since these are log-probabilities, we just subtract them. probab_ratios = np.exp(logp_new - logp_old) * reward_mask assert (B, T) == probab_ratios.shape return probab_ratios
[ "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", ".", "shape", "[", ":", "2", "]", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "p_new", ".", "shape", "[", ":", "2", "]", "logp_old", "=", "chosen_probabs", "(", "p_old", ",", "actions", ")", "logp_new", "=", "chosen_probabs", "(", "p_new", ",", "actions", ")", "assert", "(", "B", ",", "T", ")", "==", "logp_old", ".", "shape", "assert", "(", "B", ",", "T", ")", "==", "logp_new", ".", "shape", "# Since these are log-probabilities, we just subtract them.", "probab_ratios", "=", "np", ".", "exp", "(", "logp_new", "-", "logp_old", ")", "*", "reward_mask", "assert", "(", "B", ",", "T", ")", "==", "probab_ratios", ".", "shape", "return", "probab_ratios" ]
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, but using old policy network parameters. actions: ndarray of shape [B, T] where each element is from [0, A). reward_mask: ndarray of shape [B, T] masking over probabilities. Returns: probab_ratios: ndarray of shape [B, T], where probab_ratios_{b,t} = p_new_{b,t,action_{b,t}} / p_old_{b,t,action_{b,t}}
[ "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_=0.95, epsilon=0.2): """PPO objective, with an eventual minus sign, given observations.""" B, T = padded_rewards.shape # pylint: disable=invalid-name assert (B, T + 1) == padded_observations.shape[:2] assert (B, T) == padded_actions.shape assert (B, T) == padded_rewards.shape assert (B, T) == reward_mask.shape # Compute predicted values and predicted log-probs and hand it over to # `ppo_loss_given_predictions`. # (B, T+1, 1) predicted_values = value_net_apply(padded_observations, value_net_params) assert (B, T + 1, 1) == predicted_values.shape # log_probab_actions_{old,new} are both (B, T+1, A) log_probab_actions_old = policy_net_apply(padded_observations, old_policy_params) log_probab_actions_new = policy_net_apply(padded_observations, new_policy_params) assert (B, T + 1) == log_probab_actions_old.shape[:2] assert (B, T + 1) == log_probab_actions_new.shape[:2] assert log_probab_actions_old.shape[-1] == log_probab_actions_new.shape[-1] return ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, predicted_values, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon)
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_=0.95, epsilon=0.2): """PPO objective, with an eventual minus sign, given observations.""" B, T = padded_rewards.shape # pylint: disable=invalid-name assert (B, T + 1) == padded_observations.shape[:2] assert (B, T) == padded_actions.shape assert (B, T) == padded_rewards.shape assert (B, T) == reward_mask.shape # Compute predicted values and predicted log-probs and hand it over to # `ppo_loss_given_predictions`. # (B, T+1, 1) predicted_values = value_net_apply(padded_observations, value_net_params) assert (B, T + 1, 1) == predicted_values.shape # log_probab_actions_{old,new} are both (B, T+1, A) log_probab_actions_old = policy_net_apply(padded_observations, old_policy_params) log_probab_actions_new = policy_net_apply(padded_observations, new_policy_params) assert (B, T + 1) == log_probab_actions_old.shape[:2] assert (B, T + 1) == log_probab_actions_new.shape[:2] assert log_probab_actions_old.shape[-1] == log_probab_actions_new.shape[-1] return ppo_loss_given_predictions(log_probab_actions_new, log_probab_actions_old, predicted_values, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon)
[ "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_", "=", "0.95", ",", "epsilon", "=", "0.2", ")", ":", "B", ",", "T", "=", "padded_rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "padded_observations", ".", "shape", "[", ":", "2", "]", "assert", "(", "B", ",", "T", ")", "==", "padded_actions", ".", "shape", "assert", "(", "B", ",", "T", ")", "==", "padded_rewards", ".", "shape", "assert", "(", "B", ",", "T", ")", "==", "reward_mask", ".", "shape", "# Compute predicted values and predicted log-probs and hand it over to", "# `ppo_loss_given_predictions`.", "# (B, T+1, 1)", "predicted_values", "=", "value_net_apply", "(", "padded_observations", ",", "value_net_params", ")", "assert", "(", "B", ",", "T", "+", "1", ",", "1", ")", "==", "predicted_values", ".", "shape", "# log_probab_actions_{old,new} are both (B, T+1, A)", "log_probab_actions_old", "=", "policy_net_apply", "(", "padded_observations", ",", "old_policy_params", ")", "log_probab_actions_new", "=", "policy_net_apply", "(", "padded_observations", ",", "new_policy_params", ")", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "log_probab_actions_old", ".", "shape", "[", ":", "2", "]", "assert", "(", "B", ",", "T", "+", "1", ")", "==", "log_probab_actions_new", ".", "shape", "[", ":", "2", "]", "assert", "log_probab_actions_old", ".", "shape", "[", "-", "1", "]", "==", "log_probab_actions_new", ".", "shape", "[", "-", "1", "]", "return", "ppo_loss_given_predictions", "(", "log_probab_actions_new", ",", "log_probab_actions_old", ",", "predicted_values", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "gamma", ",", "lambda_", "=", "lambda_", ",", "epsilon", "=", "epsilon", ")" ]
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, gamma=0.99, lambda_=0.95, epsilon=0.2): """PPO objective, with an eventual minus sign, given predictions.""" B, T = padded_rewards.shape # pylint: disable=invalid-name assert (B, T) == padded_actions.shape assert (B, T) == reward_mask.shape _, _, A = log_probab_actions_old.shape # pylint: disable=invalid-name assert (B, T + 1, 1) == predicted_values.shape assert (B, T + 1, A) == log_probab_actions_old.shape assert (B, T + 1, A) == log_probab_actions_new.shape # (B, T) td_deltas = deltas( np.squeeze(predicted_values, axis=2), # (B, T+1) padded_rewards, reward_mask, gamma=gamma) # (B, T) advantages = gae_advantages( td_deltas, reward_mask, lambda_=lambda_, gamma=gamma) # (B, T) ratios = compute_probab_ratios(log_probab_actions_new, log_probab_actions_old, padded_actions, reward_mask) assert (B, T) == ratios.shape # (B, T) objective = clipped_objective( ratios, advantages, reward_mask, epsilon=epsilon) assert (B, T) == objective.shape # () average_objective = np.sum(objective) / np.sum(reward_mask) # Loss is negative objective. return -average_objective
python
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=0.2): """PPO objective, with an eventual minus sign, given predictions.""" B, T = padded_rewards.shape # pylint: disable=invalid-name assert (B, T) == padded_actions.shape assert (B, T) == reward_mask.shape _, _, A = log_probab_actions_old.shape # pylint: disable=invalid-name assert (B, T + 1, 1) == predicted_values.shape assert (B, T + 1, A) == log_probab_actions_old.shape assert (B, T + 1, A) == log_probab_actions_new.shape # (B, T) td_deltas = deltas( np.squeeze(predicted_values, axis=2), # (B, T+1) padded_rewards, reward_mask, gamma=gamma) # (B, T) advantages = gae_advantages( td_deltas, reward_mask, lambda_=lambda_, gamma=gamma) # (B, T) ratios = compute_probab_ratios(log_probab_actions_new, log_probab_actions_old, padded_actions, reward_mask) assert (B, T) == ratios.shape # (B, T) objective = clipped_objective( ratios, advantages, reward_mask, epsilon=epsilon) assert (B, T) == objective.shape # () average_objective = np.sum(objective) / np.sum(reward_mask) # Loss is negative objective. return -average_objective
[ "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", "=", "0.2", ")", ":", "B", ",", "T", "=", "padded_rewards", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", ")", "==", "padded_actions", ".", "shape", "assert", "(", "B", ",", "T", ")", "==", "reward_mask", ".", "shape", "_", ",", "_", ",", "A", "=", "log_probab_actions_old", ".", "shape", "# pylint: disable=invalid-name", "assert", "(", "B", ",", "T", "+", "1", ",", "1", ")", "==", "predicted_values", ".", "shape", "assert", "(", "B", ",", "T", "+", "1", ",", "A", ")", "==", "log_probab_actions_old", ".", "shape", "assert", "(", "B", ",", "T", "+", "1", ",", "A", ")", "==", "log_probab_actions_new", ".", "shape", "# (B, T)", "td_deltas", "=", "deltas", "(", "np", ".", "squeeze", "(", "predicted_values", ",", "axis", "=", "2", ")", ",", "# (B, T+1)", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "gamma", ")", "# (B, T)", "advantages", "=", "gae_advantages", "(", "td_deltas", ",", "reward_mask", ",", "lambda_", "=", "lambda_", ",", "gamma", "=", "gamma", ")", "# (B, T)", "ratios", "=", "compute_probab_ratios", "(", "log_probab_actions_new", ",", "log_probab_actions_old", ",", "padded_actions", ",", "reward_mask", ")", "assert", "(", "B", ",", "T", ")", "==", "ratios", ".", "shape", "# (B, T)", "objective", "=", "clipped_objective", "(", "ratios", ",", "advantages", ",", "reward_mask", ",", "epsilon", "=", "epsilon", ")", "assert", "(", "B", ",", "T", ")", "==", "objective", ".", "shape", "# ()", "average_objective", "=", "np", ".", "sum", "(", "objective", ")", "/", "np", ".", "sum", "(", "reward_mask", ")", "# Loss is negative objective.", "return", "-", "average_objective" ]
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_rewards, reward_mask, gamma=0.99, lambda_=0.95, epsilon=0.1): """PPO optimizer step.""" new_policy_params = trax_opt.get_params(opt_state) g = grad( ppo_loss, argnums=1)( policy_net_apply, new_policy_params, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon) return ppo_opt_update(i, g, opt_state)
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_rewards, reward_mask, gamma=0.99, lambda_=0.95, epsilon=0.1): """PPO optimizer step.""" new_policy_params = trax_opt.get_params(opt_state) g = grad( ppo_loss, argnums=1)( policy_net_apply, new_policy_params, old_policy_params, value_net_apply, value_net_params, padded_observations, padded_actions, padded_rewards, reward_mask, gamma=gamma, lambda_=lambda_, epsilon=epsilon) return ppo_opt_update(i, g, opt_state)
[ "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", ",", "gamma", "=", "0.99", ",", "lambda_", "=", "0.95", ",", "epsilon", "=", "0.1", ")", ":", "new_policy_params", "=", "trax_opt", ".", "get_params", "(", "opt_state", ")", "g", "=", "grad", "(", "ppo_loss", ",", "argnums", "=", "1", ")", "(", "policy_net_apply", ",", "new_policy_params", ",", "old_policy_params", ",", "value_net_apply", ",", "value_net_params", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "gamma", ",", "lambda_", "=", "lambda_", ",", "epsilon", "=", "epsilon", ")", "return", "ppo_opt_update", "(", "i", ",", "g", ",", "opt_state", ")" ]
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_params(opt_state) # Note this partial application here and argnums above in ppo_opt_step. g = grad(functools.partial(value_loss, value_net_apply))( value_params, padded_observations, padded_rewards, reward_mask, gamma=gamma) return opt_update(i, g, opt_state)
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_params(opt_state) # Note this partial application here and argnums above in ppo_opt_step. g = grad(functools.partial(value_loss, value_net_apply))( value_params, padded_observations, padded_rewards, reward_mask, gamma=gamma) return opt_update(i, g, opt_state)
[ "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", "(", "opt_state", ")", "# Note this partial application here and argnums above in ppo_opt_step.", "g", "=", "grad", "(", "functools", ".", "partial", "(", "value_loss", ",", "value_net_apply", ")", ")", "(", "value_params", ",", "padded_observations", ",", "padded_rewards", ",", "reward_mask", ",", "gamma", "=", "gamma", ")", "return", "opt_update", "(", "i", ",", "g", ",", "opt_state", ")" ]
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, padded_rewards, reward_mask, c1=1.0, c2=0.01, gamma=0.99, lambda_=0.95, epsilon=0.1): """Policy and Value optimizer step.""" # Combined loss function given the new params. def policy_and_value_loss(params): """Returns the combined loss given just parameters.""" (loss, _, _, _) = combined_loss( params, old_params, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, c1=c1, c2=c2, gamma=gamma, lambda_=lambda_, epsilon=epsilon) return loss new_params = trax_opt.get_params(opt_state) g = grad(policy_and_value_loss)(new_params) return opt_update(i, g, opt_state)
python
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=0.01, gamma=0.99, lambda_=0.95, epsilon=0.1): """Policy and Value optimizer step.""" # Combined loss function given the new params. def policy_and_value_loss(params): """Returns the combined loss given just parameters.""" (loss, _, _, _) = combined_loss( params, old_params, policy_and_value_net_apply, padded_observations, padded_actions, padded_rewards, reward_mask, c1=c1, c2=c2, gamma=gamma, lambda_=lambda_, epsilon=epsilon) return loss new_params = trax_opt.get_params(opt_state) g = grad(policy_and_value_loss)(new_params) return opt_update(i, g, opt_state)
[ "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", "=", "0.01", ",", "gamma", "=", "0.99", ",", "lambda_", "=", "0.95", ",", "epsilon", "=", "0.1", ")", ":", "# Combined loss function given the new params.", "def", "policy_and_value_loss", "(", "params", ")", ":", "\"\"\"Returns the combined loss given just parameters.\"\"\"", "(", "loss", ",", "_", ",", "_", ",", "_", ")", "=", "combined_loss", "(", "params", ",", "old_params", ",", "policy_and_value_net_apply", ",", "padded_observations", ",", "padded_actions", ",", "padded_rewards", ",", "reward_mask", ",", "c1", "=", "c1", ",", "c2", "=", "c2", ",", "gamma", "=", "gamma", ",", "lambda_", "=", "lambda_", ",", "epsilon", "=", "epsilon", ")", "return", "loss", "new_params", "=", "trax_opt", ".", "get_params", "(", "opt_state", ")", "g", "=", "grad", "(", "policy_and_value_loss", ")", "(", "new_params", ")", "return", "opt_update", "(", "i", ",", "g", ",", "opt_state", ")" ]
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_dir, mnli_filename, _MNLI_URL) zip_ref = zipfile.ZipFile(zip_filepath, "r") zip_ref.extractall(tmp_dir) zip_ref.close() return mnli_finalpath
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_dir, mnli_filename, _MNLI_URL) zip_ref = zipfile.ZipFile(zip_filepath, "r") zip_ref.extractall(tmp_dir) zip_ref.close() return mnli_finalpath
[ "def", "_maybe_download_corpora", "(", "tmp_dir", ")", ":", "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_dir", ",", "mnli_filename", ",", "_MNLI_URL", ")", "zip_ref", "=", "zipfile", ".", "ZipFile", "(", "zip_filepath", ",", "\"r\"", ")", "zip_ref", ".", "extractall", "(", "tmp_dir", ")", "zip_ref", ".", "close", "(", ")", "return", "mnli_finalpath" ]
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.nn.avg_pool(x, [1, 1, 1, 1], stride_spec, "VALID") path1 = tf.layers.conv2d( path1, int(output_filters / 2), (1, 1), padding="SAME", name="path1_conv") # Skip path 2. pad_arr = [[0, 0], [0, 1], [0, 1], [0, 0]] # First pad with 0's then crop. path2 = tf.pad(x, pad_arr)[:, 1:, 1:, :] path2 = tf.nn.avg_pool(path2, [1, 1, 1, 1], stride_spec, "VALID") path2 = tf.layers.conv2d( path2, int(output_filters / 2), (1, 1), padding="SAME", name="path2_conv") # Concat and apply BN. final_path = tf.concat(values=[path1, path2], axis=-1) final_path = tf.layers.batch_normalization( final_path, training=is_training, name="final_path_bn") return final_path
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.nn.avg_pool(x, [1, 1, 1, 1], stride_spec, "VALID") path1 = tf.layers.conv2d( path1, int(output_filters / 2), (1, 1), padding="SAME", name="path1_conv") # Skip path 2. pad_arr = [[0, 0], [0, 1], [0, 1], [0, 0]] # First pad with 0's then crop. path2 = tf.pad(x, pad_arr)[:, 1:, 1:, :] path2 = tf.nn.avg_pool(path2, [1, 1, 1, 1], stride_spec, "VALID") path2 = tf.layers.conv2d( path2, int(output_filters / 2), (1, 1), padding="SAME", name="path2_conv") # Concat and apply BN. final_path = tf.concat(values=[path1, path2], axis=-1) final_path = tf.layers.batch_normalization( final_path, training=is_training, name="final_path_bn") return final_path
[ "def", "shake_shake_skip_connection", "(", "x", ",", "output_filters", ",", "stride", ",", "is_training", ")", ":", "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", ".", "nn", ".", "avg_pool", "(", "x", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "stride_spec", ",", "\"VALID\"", ")", "path1", "=", "tf", ".", "layers", ".", "conv2d", "(", "path1", ",", "int", "(", "output_filters", "/", "2", ")", ",", "(", "1", ",", "1", ")", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"path1_conv\"", ")", "# Skip path 2.", "pad_arr", "=", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "1", "]", ",", "[", "0", ",", "1", "]", ",", "[", "0", ",", "0", "]", "]", "# First pad with 0's then crop.", "path2", "=", "tf", ".", "pad", "(", "x", ",", "pad_arr", ")", "[", ":", ",", "1", ":", ",", "1", ":", ",", ":", "]", "path2", "=", "tf", ".", "nn", ".", "avg_pool", "(", "path2", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "stride_spec", ",", "\"VALID\"", ")", "path2", "=", "tf", ".", "layers", ".", "conv2d", "(", "path2", ",", "int", "(", "output_filters", "/", "2", ")", ",", "(", "1", ",", "1", ")", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"path2_conv\"", ")", "# Concat and apply BN.", "final_path", "=", "tf", ".", "concat", "(", "values", "=", "[", "path1", ",", "path2", "]", ",", "axis", "=", "-", "1", ")", "final_path", "=", "tf", ".", "layers", ".", "batch_normalization", "(", "final_path", ",", "training", "=", "is_training", ",", "name", "=", "\"final_path_bn\"", ")", "return", "final_path" ]
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, stride), padding="SAME", name="conv1") x = tf.layers.batch_normalization(x, training=is_training, name="bn1") x = tf.nn.relu(x) x = tf.layers.conv2d(x, output_filters, (3, 3), padding="SAME", name="conv2") x = tf.layers.batch_normalization(x, training=is_training, name="bn2") if is_training: x = x * rand_backward + tf.stop_gradient(x * rand_forward - x * rand_backward) else: x *= 1.0 / hparams.shake_shake_num_branches return x
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, stride), padding="SAME", name="conv1") x = tf.layers.batch_normalization(x, training=is_training, name="bn1") x = tf.nn.relu(x) x = tf.layers.conv2d(x, output_filters, (3, 3), padding="SAME", name="conv2") x = tf.layers.batch_normalization(x, training=is_training, name="bn2") if is_training: x = x * rand_backward + tf.stop_gradient(x * rand_forward - x * rand_backward) else: x *= 1.0 / hparams.shake_shake_num_branches return x
[ "def", "shake_shake_branch", "(", "x", ",", "output_filters", ",", "stride", ",", "rand_forward", ",", "rand_backward", ",", "hparams", ")", ":", "is_training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "x", "=", "tf", ".", "nn", ".", "relu", "(", "x", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "x", ",", "output_filters", ",", "(", "3", ",", "3", ")", ",", "strides", "=", "(", "stride", ",", "stride", ")", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"conv1\"", ")", "x", "=", "tf", ".", "layers", ".", "batch_normalization", "(", "x", ",", "training", "=", "is_training", ",", "name", "=", "\"bn1\"", ")", "x", "=", "tf", ".", "nn", ".", "relu", "(", "x", ")", "x", "=", "tf", ".", "layers", ".", "conv2d", "(", "x", ",", "output_filters", ",", "(", "3", ",", "3", ")", ",", "padding", "=", "\"SAME\"", ",", "name", "=", "\"conv2\"", ")", "x", "=", "tf", ".", "layers", ".", "batch_normalization", "(", "x", ",", "training", "=", "is_training", ",", "name", "=", "\"bn2\"", ")", "if", "is_training", ":", "x", "=", "x", "*", "rand_backward", "+", "tf", ".", "stop_gradient", "(", "x", "*", "rand_forward", "-", "x", "*", "rand_backward", ")", "else", ":", "x", "*=", "1.0", "/", "hparams", ".", "shake_shake_num_branches", "return", "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( [batch_size, 1, 1, 1], minval=0, maxval=1, dtype=tf.float32) for _ in range(hparams.shake_shake_num_branches) ] rand_backward = [ tf.random_uniform( [batch_size, 1, 1, 1], minval=0, maxval=1, dtype=tf.float32) for _ in range(hparams.shake_shake_num_branches) ] # Normalize so that all sum to 1. total_forward = tf.add_n(rand_forward) total_backward = tf.add_n(rand_backward) rand_forward = [samp / total_forward for samp in rand_forward] rand_backward = [samp / total_backward for samp in rand_backward] zipped_rand = zip(rand_forward, rand_backward) branches = [] for branch, (r_forward, r_backward) in enumerate(zipped_rand): with tf.variable_scope("branch_{}".format(branch)): b = shake_shake_branch(x, output_filters, stride, r_forward, r_backward, hparams) b = tf.nn.dropout(b, 1.0 - hparams.layer_prepostprocess_dropout) branches.append(b) res = shake_shake_skip_connection(x, output_filters, stride, is_training) if hparams.shake_shake_concat: concat_values = [res] + branches concat_output = tf.concat(values=concat_values, axis=-1) concat_output = tf.nn.relu(concat_output) concat_output = tf.layers.conv2d( concat_output, output_filters, (1, 1), name="concat_1x1") concat_output = tf.layers.batch_normalization( concat_output, training=is_training, name="concat_bn") return concat_output else: return res + tf.add_n(branches)
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( [batch_size, 1, 1, 1], minval=0, maxval=1, dtype=tf.float32) for _ in range(hparams.shake_shake_num_branches) ] rand_backward = [ tf.random_uniform( [batch_size, 1, 1, 1], minval=0, maxval=1, dtype=tf.float32) for _ in range(hparams.shake_shake_num_branches) ] # Normalize so that all sum to 1. total_forward = tf.add_n(rand_forward) total_backward = tf.add_n(rand_backward) rand_forward = [samp / total_forward for samp in rand_forward] rand_backward = [samp / total_backward for samp in rand_backward] zipped_rand = zip(rand_forward, rand_backward) branches = [] for branch, (r_forward, r_backward) in enumerate(zipped_rand): with tf.variable_scope("branch_{}".format(branch)): b = shake_shake_branch(x, output_filters, stride, r_forward, r_backward, hparams) b = tf.nn.dropout(b, 1.0 - hparams.layer_prepostprocess_dropout) branches.append(b) res = shake_shake_skip_connection(x, output_filters, stride, is_training) if hparams.shake_shake_concat: concat_values = [res] + branches concat_output = tf.concat(values=concat_values, axis=-1) concat_output = tf.nn.relu(concat_output) concat_output = tf.layers.conv2d( concat_output, output_filters, (1, 1), name="concat_1x1") concat_output = tf.layers.batch_normalization( concat_output, training=is_training, name="concat_bn") return concat_output else: return res + tf.add_n(branches)
[ "def", "shake_shake_block", "(", "x", ",", "output_filters", ",", "stride", ",", "hparams", ")", ":", "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", "(", "[", "batch_size", ",", "1", ",", "1", ",", "1", "]", ",", "minval", "=", "0", ",", "maxval", "=", "1", ",", "dtype", "=", "tf", ".", "float32", ")", "for", "_", "in", "range", "(", "hparams", ".", "shake_shake_num_branches", ")", "]", "rand_backward", "=", "[", "tf", ".", "random_uniform", "(", "[", "batch_size", ",", "1", ",", "1", ",", "1", "]", ",", "minval", "=", "0", ",", "maxval", "=", "1", ",", "dtype", "=", "tf", ".", "float32", ")", "for", "_", "in", "range", "(", "hparams", ".", "shake_shake_num_branches", ")", "]", "# Normalize so that all sum to 1.", "total_forward", "=", "tf", ".", "add_n", "(", "rand_forward", ")", "total_backward", "=", "tf", ".", "add_n", "(", "rand_backward", ")", "rand_forward", "=", "[", "samp", "/", "total_forward", "for", "samp", "in", "rand_forward", "]", "rand_backward", "=", "[", "samp", "/", "total_backward", "for", "samp", "in", "rand_backward", "]", "zipped_rand", "=", "zip", "(", "rand_forward", ",", "rand_backward", ")", "branches", "=", "[", "]", "for", "branch", ",", "(", "r_forward", ",", "r_backward", ")", "in", "enumerate", "(", "zipped_rand", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"branch_{}\"", ".", "format", "(", "branch", ")", ")", ":", "b", "=", "shake_shake_branch", "(", "x", ",", "output_filters", ",", "stride", ",", "r_forward", ",", "r_backward", ",", "hparams", ")", "b", "=", "tf", ".", "nn", ".", "dropout", "(", "b", ",", "1.0", "-", "hparams", ".", "layer_prepostprocess_dropout", ")", "branches", ".", "append", "(", "b", ")", "res", "=", "shake_shake_skip_connection", "(", "x", ",", "output_filters", ",", "stride", ",", "is_training", ")", "if", "hparams", ".", "shake_shake_concat", ":", "concat_values", "=", "[", "res", "]", "+", "branches", "concat_output", "=", "tf", ".", "concat", "(", "values", "=", "concat_values", ",", "axis", "=", "-", "1", ")", "concat_output", "=", "tf", ".", "nn", ".", "relu", "(", "concat_output", ")", "concat_output", "=", "tf", ".", "layers", ".", "conv2d", "(", "concat_output", ",", "output_filters", ",", "(", "1", ",", "1", ")", ",", "name", "=", "\"concat_1x1\"", ")", "concat_output", "=", "tf", ".", "layers", ".", "batch_normalization", "(", "concat_output", ",", "training", "=", "is_training", ",", "name", "=", "\"concat_bn\"", ")", "return", "concat_output", "else", ":", "return", "res", "+", "tf", ".", "add_n", "(", "branches", ")" ]
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, curr_stride, hparams) return x
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, curr_stride, hparams) return x
[ "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", ")", "else", "1", "with", "tf", ".", "variable_scope", "(", "\"layer_{}\"", ".", "format", "(", "block_num", ")", ")", ":", "x", "=", "shake_shake_block", "(", "x", ",", "output_filters", ",", "curr_stride", ",", "hparams", ")", "return", "x" ]
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_norm = 0.0 # No clipping for now, one can also try 2.0. hparams.num_hidden_layers = 26 hparams.learning_rate_decay_scheme = "cosine" # Model should be run for 700000 steps with batch size 128 (~1800 epochs) hparams.learning_rate_cosine_cycle_steps = 700000 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 100 # That's basically unused. hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 1e-4 hparams.optimizer = "Momentum" hparams.optimizer_momentum_momentum = 0.9 hparams.add_hparam("shake_shake_num_branches", 2) hparams.add_hparam("shake_shake_concat", int(False)) return hparams
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_norm = 0.0 # No clipping for now, one can also try 2.0. hparams.num_hidden_layers = 26 hparams.learning_rate_decay_scheme = "cosine" # Model should be run for 700000 steps with batch size 128 (~1800 epochs) hparams.learning_rate_cosine_cycle_steps = 700000 hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 100 # That's basically unused. hparams.initializer = "uniform_unit_scaling" hparams.initializer_gain = 1.0 hparams.weight_decay = 1e-4 hparams.optimizer = "Momentum" hparams.optimizer_momentum_momentum = 0.9 hparams.add_hparam("shake_shake_num_branches", 2) hparams.add_hparam("shake_shake_concat", int(False)) return hparams
[ "def", "shakeshake_small", "(", ")", ":", "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_norm", "=", "0.0", "# No clipping for now, one can also try 2.0.", "hparams", ".", "num_hidden_layers", "=", "26", "hparams", ".", "learning_rate_decay_scheme", "=", "\"cosine\"", "# Model should be run for 700000 steps with batch size 128 (~1800 epochs)", "hparams", ".", "learning_rate_cosine_cycle_steps", "=", "700000", "hparams", ".", "learning_rate", "=", "0.2", "hparams", ".", "learning_rate_warmup_steps", "=", "100", "# That's basically unused.", "hparams", ".", "initializer", "=", "\"uniform_unit_scaling\"", "hparams", ".", "initializer_gain", "=", "1.0", "hparams", ".", "weight_decay", "=", "1e-4", "hparams", ".", "optimizer", "=", "\"Momentum\"", "hparams", ".", "optimizer_momentum_momentum", "=", "0.9", "hparams", ".", "add_hparam", "(", "\"shake_shake_num_branches\"", ",", "2", ")", "hparams", ".", "add_hparam", "(", "\"shake_shake_concat\"", ",", "int", "(", "False", ")", ")", "return", "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 steps for values. values: list<float> list of metric values. num_steps: int, number of steps the metric has to have been plateaued for. delta: float, how much the metric should have changed by over num_steps. decrease: bool, whether to check if the metric has decreased by delta or increased by delta. Returns: bool, whether the metric has plateaued. """ assert num_steps > 0 if len(steps) < 2: return False steps_at_least_num_steps_ago = [ s for s in steps if s <= (steps[-1] - num_steps) ] if not steps_at_least_num_steps_ago: # Not enough steps yet return False delta_step_idx = len(steps_at_least_num_steps_ago) - 1 start_val = values[delta_step_idx] values_to_check = values[delta_step_idx:] observed_deltas = [] for val in values_to_check: if decrease: observed_delta = start_val - val else: observed_delta = val - start_val observed_deltas.append(observed_delta) within_range = [obs < delta for obs in observed_deltas] return all(within_range)
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 steps for values. values: list<float> list of metric values. num_steps: int, number of steps the metric has to have been plateaued for. delta: float, how much the metric should have changed by over num_steps. decrease: bool, whether to check if the metric has decreased by delta or increased by delta. Returns: bool, whether the metric has plateaued. """ assert num_steps > 0 if len(steps) < 2: return False steps_at_least_num_steps_ago = [ s for s in steps if s <= (steps[-1] - num_steps) ] if not steps_at_least_num_steps_ago: # Not enough steps yet return False delta_step_idx = len(steps_at_least_num_steps_ago) - 1 start_val = values[delta_step_idx] values_to_check = values[delta_step_idx:] observed_deltas = [] for val in values_to_check: if decrease: observed_delta = start_val - val else: observed_delta = val - start_val observed_deltas.append(observed_delta) within_range = [obs < delta for obs in observed_deltas] return all(within_range)
[ "def", "has_metric_plateaued", "(", "steps", ",", "values", ",", "num_steps", "=", "100", ",", "delta", "=", "0.1", ",", "decrease", "=", "True", ")", ":", "assert", "num_steps", ">", "0", "if", "len", "(", "steps", ")", "<", "2", ":", "return", "False", "steps_at_least_num_steps_ago", "=", "[", "s", "for", "s", "in", "steps", "if", "s", "<=", "(", "steps", "[", "-", "1", "]", "-", "num_steps", ")", "]", "if", "not", "steps_at_least_num_steps_ago", ":", "# Not enough steps yet", "return", "False", "delta_step_idx", "=", "len", "(", "steps_at_least_num_steps_ago", ")", "-", "1", "start_val", "=", "values", "[", "delta_step_idx", "]", "values_to_check", "=", "values", "[", "delta_step_idx", ":", "]", "observed_deltas", "=", "[", "]", "for", "val", "in", "values_to_check", ":", "if", "decrease", ":", "observed_delta", "=", "start_val", "-", "val", "else", ":", "observed_delta", "=", "val", "-", "start_val", "observed_deltas", ".", "append", "(", "observed_delta", ")", "within_range", "=", "[", "obs", "<", "delta", "for", "obs", "in", "observed_deltas", "]", "return", "all", "(", "within_range", ")" ]
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 has to have been plateaued for. delta: float, how much the metric should have changed by over num_steps. decrease: bool, whether to check if the metric has decreased by delta or increased by delta. Returns: bool, whether the metric has plateaued.
[ "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_hparam("gan_loss", "cross_entropy") hparams.add_hparam("gan_loss_multiplier", 0.01) hparams.add_hparam("gan_vae_loss_multiplier", 0.01) hparams.add_hparam("gan_optimization", "joint") hparams.bottom = { "inputs": modalities.video_raw_bottom, "targets": modalities.video_raw_targets_bottom, } hparams.loss = { "targets": modalities.video_l1_raw_loss, } hparams.top = { "targets": modalities.video_raw_top, } hparams.latent_loss_multiplier_schedule = "linear" hparams.upsample_method = "bilinear_upsample_conv" hparams.internal_loss = False hparams.reward_prediction = False hparams.anneal_end = 100000 hparams.num_iterations_1st_stage = 0 hparams.num_iterations_2nd_stage = 50000 return hparams
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_hparam("gan_loss", "cross_entropy") hparams.add_hparam("gan_loss_multiplier", 0.01) hparams.add_hparam("gan_vae_loss_multiplier", 0.01) hparams.add_hparam("gan_optimization", "joint") hparams.bottom = { "inputs": modalities.video_raw_bottom, "targets": modalities.video_raw_targets_bottom, } hparams.loss = { "targets": modalities.video_l1_raw_loss, } hparams.top = { "targets": modalities.video_raw_top, } hparams.latent_loss_multiplier_schedule = "linear" hparams.upsample_method = "bilinear_upsample_conv" hparams.internal_loss = False hparams.reward_prediction = False hparams.anneal_end = 100000 hparams.num_iterations_1st_stage = 0 hparams.num_iterations_2nd_stage = 50000 return hparams
[ "def", "next_frame_savp", "(", ")", ":", "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_hparam", "(", "\"gan_loss\"", ",", "\"cross_entropy\"", ")", "hparams", ".", "add_hparam", "(", "\"gan_loss_multiplier\"", ",", "0.01", ")", "hparams", ".", "add_hparam", "(", "\"gan_vae_loss_multiplier\"", ",", "0.01", ")", "hparams", ".", "add_hparam", "(", "\"gan_optimization\"", ",", "\"joint\"", ")", "hparams", ".", "bottom", "=", "{", "\"inputs\"", ":", "modalities", ".", "video_raw_bottom", ",", "\"targets\"", ":", "modalities", ".", "video_raw_targets_bottom", ",", "}", "hparams", ".", "loss", "=", "{", "\"targets\"", ":", "modalities", ".", "video_l1_raw_loss", ",", "}", "hparams", ".", "top", "=", "{", "\"targets\"", ":", "modalities", ".", "video_raw_top", ",", "}", "hparams", ".", "latent_loss_multiplier_schedule", "=", "\"linear\"", "hparams", ".", "upsample_method", "=", "\"bilinear_upsample_conv\"", "hparams", ".", "internal_loss", "=", "False", "hparams", ".", "reward_prediction", "=", "False", "hparams", ".", "anneal_end", "=", "100000", "hparams", ".", "num_iterations_1st_stage", "=", "0", "hparams", ".", "num_iterations_2nd_stage", "=", "50000", "return", "hparams" ]
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_multiplier_schedule", "=", "\"linear_anneal\"", "return", "hparams" ]
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_steps = 100000 hparams.learning_rate_schedule = "constant*linear_decay" return hparams
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_steps = 100000 hparams.learning_rate_schedule = "constant*linear_decay" return hparams
[ "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", "=", "0.5", "hparams", ".", "learning_rate_constant", "=", "2e-4", "hparams", ".", "gan_loss", "=", "\"cross_entropy\"", "hparams", ".", "learning_rate_decay_steps", "=", "100000", "hparams", ".", "learning_rate_schedule", "=", "\"constant*linear_decay\"", "return", "hparams" ]
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, learning_rate_warmup_steps=2000, learning_rate_decay_scheme="noam", # "noam" or "none" epsilon=1e-10, beta1=0.0, # we can save memory if beta1=0 beta2=0.98, factored_second_moment_accumulator=True, # this saves memory )
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, learning_rate_warmup_steps=2000, learning_rate_decay_scheme="noam", # "noam" or "none" epsilon=1e-10, beta1=0.0, # we can save memory if beta1=0 beta2=0.98, factored_second_moment_accumulator=True, # this saves memory )
[ "def", "diet_adam_optimizer_params", "(", ")", ":", "return", "hparam", ".", "HParams", "(", "quantize", "=", "True", ",", "# use 16-bit fixed-point", "quantization_scale", "=", "10.0", "/", "tf", ".", "int16", ".", "max", ",", "optimizer", "=", "\"DietAdam\"", ",", "learning_rate", "=", "1.0", ",", "learning_rate_warmup_steps", "=", "2000", ",", "learning_rate_decay_scheme", "=", "\"noam\"", ",", "# \"noam\" or \"none\"", "epsilon", "=", "1e-10", ",", "beta1", "=", "0.0", ",", "# we can save memory if beta1=0", "beta2", "=", "0.98", ",", "factored_second_moment_accumulator", "=", "True", ",", "# this saves memory", ")" ]
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 HParams object. Returns: a Tensor with shape [batch, io_size] """ @fn_with_diet_vars(params) def diet_expert_internal(x): dim = x.get_shape().as_list()[-1] h = tf.layers.dense(x, hidden_size, activation=tf.nn.relu, use_bias=False) y = tf.layers.dense(h, dim, use_bias=False) y *= tf.rsqrt(tf.to_float(dim * hidden_size)) return y return diet_expert_internal(x)
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 HParams object. Returns: a Tensor with shape [batch, io_size] """ @fn_with_diet_vars(params) def diet_expert_internal(x): dim = x.get_shape().as_list()[-1] h = tf.layers.dense(x, hidden_size, activation=tf.nn.relu, use_bias=False) y = tf.layers.dense(h, dim, use_bias=False) y *= tf.rsqrt(tf.to_float(dim * hidden_size)) return y return diet_expert_internal(x)
[ "def", "diet_expert", "(", "x", ",", "hidden_size", ",", "params", ")", ":", "@", "fn_with_diet_vars", "(", "params", ")", "def", "diet_expert_internal", "(", "x", ")", ":", "dim", "=", "x", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "-", "1", "]", "h", "=", "tf", ".", "layers", ".", "dense", "(", "x", ",", "hidden_size", ",", "activation", "=", "tf", ".", "nn", ".", "relu", ",", "use_bias", "=", "False", ")", "y", "=", "tf", ".", "layers", ".", "dense", "(", "h", ",", "dim", ",", "use_bias", "=", "False", ")", "y", "*=", "tf", ".", "rsqrt", "(", "tf", ".", "to_float", "(", "dim", "*", "hidden_size", ")", ")", "return", "y", "return", "diet_expert_internal", "(", "x", ")" ]
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 [batch, io_size]
[ "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 = abs_x / params.quantization_scale y = tf.floor(y + tf.random_uniform(common_layers.shape_list(x))) y = tf.minimum(y, tf.int16.max) * sign_x q = tf.bitcast(tf.cast(y, tf.int16), tf.float16) return q
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 = abs_x / params.quantization_scale y = tf.floor(y + tf.random_uniform(common_layers.shape_list(x))) y = tf.minimum(y, tf.int16.max) * sign_x q = tf.bitcast(tf.cast(y, tf.int16), tf.float16) return q
[ "def", "_quantize", "(", "x", ",", "params", ",", "randomize", "=", "True", ")", ":", "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", "=", "abs_x", "/", "params", ".", "quantization_scale", "y", "=", "tf", ".", "floor", "(", "y", "+", "tf", ".", "random_uniform", "(", "common_layers", ".", "shape_list", "(", "x", ")", ")", ")", "y", "=", "tf", ".", "minimum", "(", "y", ",", "tf", ".", "int16", ".", "max", ")", "*", "sign_x", "q", "=", "tf", ".", "bitcast", "(", "tf", ".", "cast", "(", "y", ",", "tf", ".", "int16", ")", ",", "tf", ".", "float16", ")", "return", "q" ]
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", ".", "quantization_scale" ]
Dequantize q according to params.
[ "Dequantize", "q", "according", "to", "params", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/diet.py#L253-L257