text
stringlengths
81
112k
Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max value k times. The running time is proportional to k, which is be faster when k is small. The current implementation supports only inputs of rank 2. In addition, iota is used to replace t...
Given sequences and scores, will gather the top k=beam size sequences. This function is used to grow alive, and finished. It takes sequences, scores, and flags, and returns the top k from sequences, scores_to_gather, and flags based on the values in scores. This method permits easy introspection using tfdbg. ...
Beam search with length penalties. Requires a function that can take the currently decoded symbols and return the logits for the next symbol. The implementation is inspired by https://arxiv.org/abs/1609.08144. When running, the beam search steps can be visualized by using tfdbg to watch the operations gener...
Augments video with optional hue, saturation and constrast. Args: features: dict, with keys "inputs", "targets". features["inputs"], 4-D Tensor, shape=(THWC) features["targets"], 4-D Tensor, shape=(THWC) hue: bool, apply hue_transform. saturate: bool, apply saturation transfor...
Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. color: string, "blue", "red" or "green". border_percent: Percentarge of the frame covered by the border. Returns: video: 5-D NumPy array. def create_border(video, color="blue", border_percent=2): ...
Converts input, output and target videos into video summaries. Args: input_videos: 5-D NumPy array, (NTHWC) conditioning frames. output_videos: 5-D NumPy array, (NTHWC) model predictions. target_videos: 5-D NumPy array, (NTHWC) target frames. tag: tf summary tag. decode_hparams: HParams. disp...
Hooks to display videos at decode time. def display_video_hooks(hook_args): """Hooks to display videos at decode time.""" predictions = hook_args.predictions max_outputs = hook_args.decode_hparams.max_display_outputs max_decodes = hook_args.decode_hparams.max_display_decodes with tf.Graph().as_default(): ...
Computes video metrics summaries using the decoder output. def summarize_video_metrics(hook_args): """Computes video metrics summaries using the decoder output.""" problem_name = hook_args.problem.name current_problem = hook_args.problem hparams = hook_args.hparams output_dirs = hook_args.output_dirs predi...
Creates a VideoWriter for debug videos. def debug_video_writer_factory(output_dir): """Creates a VideoWriter for debug videos.""" if FLAGS.disable_ffmpeg: return common_video.IndividualFrameWriter(output_dir) else: output_path = os.path.join(output_dir, "video.avi") return common_video.WholeVideoWrit...
Runtime preprocessing, e.g., resize example["frame"]. def preprocess_example(self, example, mode, hparams): """Runtime preprocessing, e.g., resize example["frame"].""" if getattr(hparams, "preprocess_resize_frames", None) is not None: example["frame"] = tf.image.resize_images( example["frame"],...
For serving/predict, assume that only video frames are provided. def serving_input_fn(self, hparams): """For serving/predict, assume that only video frames are provided.""" video_input_frames = tf.placeholder( dtype=tf.float32, shape=[ None, hparams.video_num_input_frames, self.fram...
Generate samples of the encoded frames with possible extra data. By default this function just encodes the numpy array returned as "frame" from `self.generate_samples` into a PNG image. Override this function to get other encodings on disk. Args: data_dir: final data directory. Typically only us...
The function generating the data. def generate_data(self, data_dir, tmp_dir, task_id=-1): """The function generating the data.""" filepath_fns = { problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_fil...
Return a decorator which add a TF name/variable scope to a function. Note that the function returned by the decorator accept an additional 'name' parameter, which can overwrite the name scope given when the function is created. Args: scope (str): name of the scope. If None, the function name is used. ...
Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var def _add_variable_proxy_methods(var, proxy_tensor): """Proxy methods of underlying variable. This enables our custom g...
UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an integer `Tensor` with shape `[batch_size, k]`. n: an integer. Returns: A `Tensor` with the same type as `values` and shape `[batch_size, n]`. def _rowwise_unsorted_segment_sum(values, indices, n): ...
Helper function to NoisyTopKGating. Computes the probability that value is in top k, given different random noise. This gives us a way of backpropagating from a loss that balances the number of times each expert is in the top k experts per example. In the case of no noise, pass in None for noise_stddev, and ...
The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added for numerical stability. Returns 0 for an empty Tensor. Args: x: a `Tensor`. Returns: a `Scalar`. def cv_squared(x): """The squared coefficient of variation ...
VQ Gating hparams. def update_hparams_for_vq_gating(hparams): """VQ Gating hparams.""" hparams.add_hparam("z_size", 4) hparams.add_hparam("noise_dev", 0.5) # Bottleneck kinds supported: dense, vae, dvq. hparams.add_hparam("bottleneck_kind", "dvq") hparams.add_hparam("num_blocks", 1) hparams.add_hparam("n...
GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense, seems not to be, so if we use tf.nn.top_k, then both the top_k and its gradient go on cpu. Once this is not an issue, this function becomes o...
VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer k: an integer - number of experts per example bneck: a bottleneck object hparams: optional hparams name: an optional string Returns: gates: a Tensor with shape [batch_size, num_experts] loa...
Noisy top-k gating. See paper: https://arxiv.org/abs/1701.06538. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an integer train: a boolean - we only add noise at training time. k: an integer - number of experts per example initializer: an initializer noisy_gating: ...
Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch independently. This is similar to tf.map_fn but with tensor where the batch dim has been flatten. Warning: The indices ids have to be contiguous and ordered in memory as the output vector for ...
Returns a function that creates a feed-forward network. Use this function to create the expert_fn argument to distributed_moe. Args: input_size: an integer hidden_sizes: a list of integers output_size: an integer hidden_activation: a unary function. Returns: a unary function def ffn_expert...
Flatten all dimensions of a except the last. def flatten_all_but_last(a): """Flatten all dimensions of a except the last.""" ret = tf.reshape(a, [-1, tf.shape(a)[-1]]) if not tf.executing_eagerly(): ret.set_shape([None] + a.get_shape().as_list()[-1:]) return ret
Call a local mixture of experts. Args: x: a tensors with shape [... , input_size] train: a boolean scalar. expert_fn: a function. num_experts: an integer - number of experts k: an integer - how many experts to use for each batch element loss_coef: a scalar - multiplier on load-balancing losse...
Local mixture of experts that works well on TPU. See https://arxiv.org/abs/1701.06538 There are num_experts expert networks, each containing a relu-activated hidden layer of size hidden_size, followed by an output projection. The number of parameters is thus: num_experts * (input_size * hidden_size + hid...
Reduces data per device. This can be useful, for example, if we want to all-reduce n tensors on k<n devices (like during eval when we have only one device). We call reduce_by_device() to first sum the tensors per device, then call our usual all-reduce operation to create one sum per device, followed by expa...
Opposite of reduce_by_device(). Args: original_parallelism: a expert_utils.Parallelism object. device_parallelism: a expert_utils.Parallelism object. data: a list of tensors with length device_parallelism.n Returns: a list of Tensors with length original_parallelism.n def expand_by_device(origina...
Compute the sum of all Tensors and put the result everywhere. Assumes that the devices are connected in a ring. Args: x: a list of Tensors with length parallelism.n parallelism: a expert_utils.Parallelism object. maybe_reduce: a boolean - first reduce per device. use_bfloat16: a boolean - saves ba...
Utility function for processing arguments that are singletons or lists. Args: x: either a list of self.n elements, or not a list. Returns: a list of self.n elements. def _maybe_repeat(self, x): """Utility function for processing arguments that are singletons or lists. Args: x: eith...
Remove padding from the given tensor. Args: x (tf.Tensor): of shape [dim_origin,...] Returns: a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin def remove(self, x): """Remove padding from the given tensor. Args: x (tf.Tensor): of shape [dim_origin,...] R...
Add padding back to the given tensor. Args: x (tf.Tensor): of shape [dim_compressed,...] Returns: a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The dim is restored from the original reference tensor def restore(self, x): """Add padding back to the given tensor. ...
Create one input Tensor for each expert. The `Tensor` for a expert `i` contains the slices of `inp` corresponding to the batch elements `b` where `gates[b, i] > 0`. Args: inp: a `Tensor` of shape "[batch_size, <extra_input_dims>]` Returns: a list of `num_experts` `Tensor`s with shapes ...
Sum together the expert output, weighted by the gates. The slice corresponding to a particular batch element `b` is computed as the sum over all experts `i` of the expert output, weighted by the corresponding gate values. If `multiply_by_gates` is set to False, the gate values are ignored. Args: ...
Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32` and shapes `[expert_batch_size_i]` def expert_to_gates(self): """Gate values corresponding to the examples in the per-expert `Tensor`s. ...
Batch indices corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64` and shapes `[expert_batch_size_i]` def expert_to_batch_indices(self): """Batch indices corresponding to the examples in the per-expert `Tenso...
Create one input Tensor for each expert. Args: inp: a list of length num_datashards `Tensor`s with shapes `[batch_size[d], <extra_input_dims>]`. Returns: a list of `num_experts` `Tensor`s with shapes `[num_examples[i], <extra_input_dims>]`. def dispatch(self, inp): """Create on...
Sum together the expert output, multiplied by the corresponding gates. Args: expert_out: a list of `num_experts` `Tensor`s, each with shape `[expert_batch_size_i, <extra_output_dims>]`. multiply_by_gates: a boolean. Returns: a list of num_datashards `Tensor`s with shapes `[ba...
Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `Tensor`s of type `tf.float32`. def expert_to_gates(self): """Gate values corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dim...
Send the inputs to the experts. Args: inp: a `Tensor` of shape "[batch, length, depth]` Returns: a tensor with shape [batch, num_experts, expert_capacity, depth] def dispatch(self, inp): """Send the inputs to the experts. Args: inp: a `Tensor` of shape "[batch, length, depth]` R...
Return the output from the experts. When one example goes to multiple experts, the outputs are summed. Args: x: a Tensor with shape [batch, num_experts, expert_capacity, depth] Returns: a `Tensor` with shape `[batch, length, depth] def combine(self, x): """Return the output from the expe...
Factory function for envs. def make_env(env_type, real_env, sim_env_kwargs): """Factory function for envs.""" return { "real": lambda: real_env.new_like( # pylint: disable=g-long-lambda batch_size=sim_env_kwargs["batch_size"], store_rollouts=False, ), "simulated": lambda: rl_...
Factory function for Agents. def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None, batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs ): """Factory function for Agents.""" if batch_size is...
Collects frames from real env for random starts of simulated env. def collect_frames_for_random_starts( storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit, log_every_steps=None ): """Collects frames from real env for random starts of simulated env.""" del frame_stack_size storage...
Creates an Agent from hparams. def make_agent_from_hparams( agent_type, base_env, stacked_env, loop_hparams, policy_hparams, planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=() ): """Creates an Agent from hparams.""" def sim_env_kwargs_fn(): return rl.make_simulated_env_kwargs( ...
Returns an out-of-graph eval_fn using the Agent API. def make_eval_fn_with_agent( agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None, video_writers=(), random_starts_step_limit=None ): """Returns an out-of-graph eval_fn using the Agent API.""" def eval_fn(env, loop_hparams, policy_hpar...
Evaluates the world model. def evaluate_world_model( agent_type, loop_hparams, planner_hparams, model_dir, policy_dir, random_starts_step_limit, debug_video_path, log_every_steps ): """Evaluates the world model.""" if debug_video_path: debug_video_path = os.path.join(debug_video_path, "0.avi") stora...
Evaluate. def evaluate( loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir, agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path, num_debug_videos=1, random_starts_step_limit=None, report_fn=None, report_metric=None ): """Evaluate.""" if eval_with_learner:...
Get game for the given worker (directory) id. def get_game_for_worker(map_name, directory_id): """Get game for the given worker (directory) id.""" if map_name == "v100unfriendly": games = ["chopper_command", "boxing", "asterix", "seaquest"] worker_per_game = 5 elif map_name == "human_nice": games = g...
Given a representation of the board, returns a list of open spaces. def get_open_spaces(board): """Given a representation of the board, returns a list of open spaces.""" open_spaces = [] for i in range(3): for j in range(3): if board[i][j] == 0: open_spaces.append(encode_pos(i, j)) return ope...
Given a representation of the board, returns reward and done. def get_reward_and_done(board): """Given a representation of the board, returns reward and done.""" # Returns (reward, done) where: # reward: -1 means lost, +1 means win, 0 means draw or continuing. # done: True if the game is over, i.e. someone won...
Hyperparameters for decoding. def decode_hparams(overrides=""): """Hyperparameters for decoding.""" hp = hparam.HParams( save_images=False, log_results=True, extra_length=100, min_length_ratio=0.0, batch_size=0, beam_size=4, alpha=0.6, eos_penalty=0.0, block_si...
Log inference results. def log_decode_results(inputs, outputs, problem_name, prediction_idx, inputs_vocab, targets_vocab, targets=None, save_images=False, ...
Perform decoding from dataset. def decode_from_dataset(estimator, problem_name, hparams, decode_hp, decode_to_file=None, dataset_split=None, checkpoint_path=None): """Perfor...
Decodes once. Args: estimator: tf.estimator.Estimator instance. Used to generate encoded predictions. problem_name: str. Name of problem. hparams: HParams instance. HParams for model training. infer_input_fn: zero-arg function. Input function for estimator. decode_hp: HParams instance. See ...
Compute predictions on entries in filename and write them out. def decode_from_file(estimator, filename, hparams, decode_hp, decode_to_file=None, checkpoint_path=None): """Compute predictions on entries in filena...
Generates decode filename. Args: base_filename: A string, base of the decode filename. problem_name: A string, name of the problem. decode_hp: HParams for decoding. Returns: A string, produced decode filename. def _decode_filename(base_filename, problem_name, decode_hp): """Generates decode fil...
Use py_func to yield elements from the given generator. def make_input_fn_from_generator(gen): """Use py_func to yield elements from the given generator.""" first_ex = six.next(gen) flattened = tf.contrib.framework.nest.flatten(first_ex) types = [t.dtype for t in flattened] shapes = [[None] * len(t.shape) fo...
Interactive decoding. def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None): """Interactive decoding.""" is_image = "image" in hparams.problem.name is_text2class = isinstance(hparams.problem, text_problems.Text2ClassProblem) skip_eos_postprocess = ( i...
Generator to produce batches of inputs. def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary, batch_size, max_input_size, task_id=-1, has_input=True): """Generator to produce batches of inputs.""" tf.logging.info(" batch %d" % num_decode_bat...
Generator that reads from the terminal and yields "interactive inputs". Due to temporary limitations in tf.learn, if we don't want to reload the whole graph, then we are stuck encoding all of the input as one fixed-size numpy array. We yield int32 arrays with shape [const_array_size]. The format is: [num_s...
Save frames of the videos into files. def save_video(video, save_path_template): """Save frames of the videos into files.""" try: from PIL import Image # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Showing and saving an image requires PIL library to be " ...
Shows an image using matplotlib and saves it. def show_and_save_image(img, save_path): """Shows an image using matplotlib and saves it.""" try: import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Showing and saving an image requires...
Read a file of partial texts to continue. The purpose of append_space_to_final_punctionation is that SubwordTokenizer groups punctuation and the ensuing space in the same token. Adding a space causes the token to be completed. Args: filename: a string delimiter: a string repeat: an integer - we r...
Returning inputs sorted according to decreasing length. This causes inputs of similar lengths to be processed in the same batch, facilitating early stopping for short sequences. Longer sequences are sorted first so that if you're going to get OOMs, you'll see it in the first batch. Args: filename: path...
Strips everything after the first <EOS> token, which is normally 1. def _save_until_eos(ids, skip=False): """Strips everything after the first <EOS> token, which is normally 1.""" ids = ids.flatten() if skip: return ids try: index = list(ids).index(text_encoder.EOS_ID) return ids[0:index] except ...
Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder. def _interactive_input_tensor_to_features_dict(feature_map, hparams): """Convert the interactive input fo...
Convert the interactive input format (see above) to a dictionary. Args: feature_map: dict with inputs. hparams: model hyperparameters Returns: a features dictionary, as expected by the decoder. def _decode_input_tensor_to_features_dict(feature_map, hparams): """Convert the interactive input format ...
Run hooks after decodes have run. def run_postdecode_hooks(decode_hook_args, dataset_split): """Run hooks after decodes have run.""" hooks = decode_hook_args.problem.decode_hooks if not hooks: return global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir) if global_step is None: tf...
Splits of data to produce and number of output shards for each. def dataset_splits(self): """Splits of data to produce and number of output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": _TRAIN_SHARDS, }, { "split": problem.DatasetSplit.EVAL, "s...
Image Transformer decoder with local1D spatial layers. def local_attention1d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_w_dim = mtf.Dimen...
Image Transformer decoder with local2D spatial layers. def local_attention2d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local2D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_h_dim = mtf.Dimen...
Image Transformer decoder with local1D masked layers. def local_attention1d_masked_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D masked layers.""" print(x) _, length_dim, model_dim = x.shape.dims for layer in range(hparam...
Set of hyperparameters. def mtf_image_transformer_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.no_data_parallelism = True hparams.use_fixed_batch_size = True hparams.batch_size = 1 hparams.max_length = 3072 hparams.hidden_size = 256 hparams.label_smoothing = 0....
Catch bugs locally... def mtf_image_transformer_tiny(): """Catch bugs locally...""" hparams = mtf_image_transformer_base() hparams.hidden_size = 128 hparams.d_ff = 256 hparams.batch_size = 4 hparams.num_encoder_layers = 1 hparams.num_decoder_layers = 4 hparams.num_heads = 4 hparams.attention_key_size...
Small single parameters. def mtf_image_transformer_single(): """Small single parameters.""" hparams = mtf_image_transformer_tiny() hparams.mesh_shape = "" hparams.layout = "" hparams.hidden_size = 32 hparams.filter_size = 32 hparams.batch_size = 1 hparams.num_encoder_layers = 1 hparams.num_decoder_la...
Small single parameters. def mtf_image_transformer_base_single(): """Small single parameters.""" hparams = mtf_image_transformer_base() hparams.num_decoder_layers = 6 hparams.filter_size = 256 hparams.block_length = 128 hparams.mesh_shape = "" hparams.layout = "" return hparams
Small single parameters. def mtf_image_transformer_tiny_spatial1d(): """Small single parameters.""" hparams = mtf_image_transformer_tiny() hparams.num_decoder_layers = 6 hparams.filter_size = 128 hparams.block_height = 8 hparams.block_width = 8 hparams.attention_type = "local1d_spatial" hparams.mesh_sh...
Data parallel CIFAR parameters. def mtf_image_transformer_base_cifar(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base() hparams.mesh_shape = "batch:8" hparams.layout = "batch:batch" hparams.learning_rate_decay_steps = 13600 # one epoch hparams.batch_size = 32 hparams.num_hea...
Data parallel CIFAR parameters. def mtf_image_transformer_cifar_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 return hparams
Data parallel CIFAR parameters. def mtf_image_transformer_cifar_mp_4x(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "model:4;batch:8" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 32 hparams.num_heads = 8 hparams.d_...
Data parallel CIFAR parameters. def mtf_image_transformer_base_imagenet(): """Data parallel CIFAR parameters.""" hparams = mtf_image_transformer_base_cifar() hparams.mesh_shape = "batch:32" hparams.layout = "batch:batch" hparams.batch_size = 128 hparams.d_ff = 2048 hparams.hidden_size = 512 hparams.num...
Model parallel ImageNet parameters. def mtf_image_transformer_base_imagenet_mp(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:4;batch:8" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 32 hparams.num_heads ...
Model parallel ImageNet parameters. def mtf_image_transformer_base_imagenet_mp128(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 8 hparams.img_len ...
Model parallel ImageNet parameters. def mtf_image_transformer_base_imagenet_mp_sp(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet_mp128() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;num_wblocks:model" hparams.batch_size = 8 hpar...
Model parallel ImageNet parameters. def mtf_image_transformer_base_imagenet_mp64(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 8 hparams.img_len =...
Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output units always have the same degree as their associated input unit. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per...
Returns a list of binary mask matrices respecting autoregressive ordering. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer; those number of units will always be set to input_dim downstream. Each hidden unit size ...
Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column normalization. -To ensure positivity...
Random variable for f(x), where x ~ p(x) and f is reversible. def TransformedRandomVariable(random_variable, # pylint: disable=invalid-name reversible_layer, name=None, sample_shape=(), value=None):...
Returns log det | dx / dy | = num_events * sum log | scale |. def log_det_jacobian(self, inputs): """Returns log det | dx / dy | = num_events * sum log | scale |.""" del inputs # unused # Number of events is number of all elements excluding the batch and # channel dimensions. num_events = tf.reduc...
Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim]. def slice_hidden(self, x): """Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-...
Find the nearest element in means to elements in x. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means of shape. Returns: Tensor with nearest element in mean encoded in one-hot notation. def neare...
Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor in one hot form, the nearest neighbor ...
Turn x_int representing numbers into a bitwise (lower-endian) tensor. Args: x_int: Tensor containing integer to be converted into base notation. num_bits: Number of bits in the representation. base: Base of the representation. Returns: Corresponding number expressed in ...
Embedding function that takes discrete latent and returns embedding. Args: x: Input to the discretization bottleneck. Returns: Continuous embedding to be passed on to the decoder. Raises: ValueError: For unknown or missing arguments. def embed(self, x): """Embedding function t...
Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass to the decoder, discrete latent, loss, and the embedding function. Raises: ValueError: If projection_tensors is None for reshape_method ...
Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon and beta1 correction. Args: hparams: model hyperparameters where "adam" in hparams.optimizer def mimic_adam_with_adafactor(hparams): """Switch from Adam to Adafactor, approximating the behavi...
Old version - Adam. def afx_adam(): """Old version - Adam.""" hparams = transformer.transformer_base_v2() hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.symbol_modality_num_shards = 1 hparams.batch_size = 2048 hparams.optimizer = "adam" hparams.learning_rate_schedule = ...