INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Run the model and extract samples. Args: features: an map of string to `Tensor`. Returns: samples: an integer `Tensor`. logits: a list of `Tensor`s, one per datashard. losses: a dictionary: {loss-name (string): floating point `Scalar`}.
def sample(self, features): """Run the model and extract samples. Args: features: an map of string to `Tensor`. Returns: samples: an integer `Tensor`. logits: a list of `Tensor`s, one per datashard. losses: a dictionary: {loss-name (string): floating point `Scalar`}. """ ...
Model fn for Estimator. Args: hparams: HParams, model hyperparameters features: dict<str name, Tensor feature> labels: Tensor mode: tf.estimator.ModeKeys config: RunConfig, possibly with data_parallelism attribute params: dict, may include batch_size, use_tpu decode_hparam...
def estimator_model_fn(cls, hparams, features, labels, mode, config=None, params=None, decode_hparams=None, use_tpu=Fals...
Constructs `tf.estimator.EstimatorSpec` for TRAIN (training) mode.
def estimator_spec_train(self, loss, num_async_replicas=1, use_tpu=False): """Constructs `tf.estimator.EstimatorSpec` for TRAIN (training) mode.""" train_op = self.optimize(loss, num_async_replicas=num_async_replicas, use_tpu=use_tpu) if use_tpu: if self._hparams.warm_sta...
Constructs `tf.estimator.EstimatorSpec` for EVAL (evaluation) mode.
def estimator_spec_eval(self, features, logits, labels, loss, losses_dict): """Constructs `tf.estimator.EstimatorSpec` for EVAL (evaluation) mode.""" del losses_dict hparams = self.hparams if not hasattr(hparams, "problem"): raise NotImplementedError(_no_problem_err("estimator_spec_eval")) p...
Constructs `tf.estimator.EstimatorSpec` for PREDICT (inference) mode.
def estimator_spec_predict(self, features, use_tpu=False): """Constructs `tf.estimator.EstimatorSpec` for PREDICT (inference) mode.""" decode_hparams = self._decode_hparams top_beams = decode_hparams.beam_size if decode_hparams.return_beams else 1 infer_out = self.infer( features, beam_s...
Adds `tf.summary`s to all terms in the losses dictionary.
def _summarize_losses(self, losses_dict): """Adds `tf.summary`s to all terms in the losses dictionary.""" if common_layers.should_generate_summaries(): with tf.name_scope("losses"): for loss_name, loss_val in sorted(losses_dict.items()): tf.summary.scalar(loss_name, loss_val)
Scheduled sampling. Performs forward inference again with "targets" feature replaced with values sampled from the model. This is the identity unless self.hparams.scheduled_sampling_prob > 0 (default). **WARNING**: This is not a faithful implementation of scheduled sampling. This implementatio...
def maybe_scheduled_sampling(self, features, logits, losses): """Scheduled sampling. Performs forward inference again with "targets" feature replaced with values sampled from the model. This is the identity unless self.hparams.scheduled_sampling_prob > 0 (default). **WARNING**: This is not a ...
Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values to implement masked attention and possibly biases for diagonal...
def attention_lm_moe_prepare_decoder(targets, hparams): """Prepare one shard of the model for the decoder. Args: targets: a Tensor. hparams: run hyperparameters Returns: decoder_input: a Tensor, bottom of decoder stack decoder_self_attention_bias: a Tensor, containing large negative values t...
Return a flat int32 tensor of shape [1, batch_size*length, 1].
def get_batch_coordinate(x, axis=0): """Return a flat int32 tensor of shape [1, batch_size*length, 1].""" # Compute the batch coordinate before flattening all batches batch_coordinate = tf.expand_dims( common_attention.coordinate_tensor(tf.shape(x)[:-1], axis=axis), axis=-1) return batch_coordinate
Duplicate elements of bc by length_factor. Args: bc (tf.Tensor): int32 tensor of shape [1, length, 1] length_factor (int): Returns: tf.Tensor: of shape [1, length*length_factor, 1] where every elements has been duplicated length_factor times.
def expand_batch_coordinates(bc, length_factor): """Duplicate elements of bc by length_factor. Args: bc (tf.Tensor): int32 tensor of shape [1, length, 1] length_factor (int): Returns: tf.Tensor: of shape [1, length*length_factor, 1] where every elements has been duplicated length_factor times....
Remove padding by concatenating all dimension into one. Args: x (tf.Tensor): input of shape [batch_size, length, depth] pad_remover (obj): a PadRemover object mode (ModeKeys): infer, train or eval. If inference, the padding remover is not applied Returns: tf.Tensor of shape [1,length_nonpad,...
def remove_pad(x, pad_remover, mode): """Remove padding by concatenating all dimension into one. Args: x (tf.Tensor): input of shape [batch_size, length, depth] pad_remover (obj): a PadRemover object mode (ModeKeys): infer, train or eval. If inference, the padding remover is not applied Return...
Set of hyperparameters. suitable for 1 gpu. on lm1b_32k: ~229M params 0.9 steps/sec on [GeForce GTX TITAN X] Returns: a hparams object
def attention_lm_moe_base(): """Set of hyperparameters. suitable for 1 gpu. on lm1b_32k: ~229M params 0.9 steps/sec on [GeForce GTX TITAN X] Returns: a hparams object """ hparams = common_hparams.basic_params1() hparams.hidden_size = 1024 hparams.batch_size = 8192 hparams.max_length =...
Hyper parameters specifics for long sequence generation.
def attention_lm_moe_base_long_seq(): """Hyper parameters specifics for long sequence generation.""" hparams = attention_lm_moe_base() hparams.max_length = 0 # max_length == batch_size hparams.eval_drop_long_sequences = True hparams.min_length_bucket = 256 # Avoid cyclic problems for big batches hparams....
Base model with attention expert.
def attention_lm_moe_base_ae(): """Base model with attention expert.""" hparams = attention_lm_moe_base_long_seq() hparams.attention_type = AttentionType.LOCAL_EXPERTS hparams.learning_rate = 0.05 hparams.learning_rate_warmup_steps = 10000 # According to noam, ("n", "da") seems better for harder-to-learn m...
Experiment with the exp_factor params.
def attention_lm_ae_extended(): """Experiment with the exp_factor params.""" hparams = attention_lm_moe_base_long_seq() hparams.attention_layers = "eeee" hparams.attention_local = True # hparams.factored_logits=1 # Necessary when the number of expert grow bigger hparams.attention_moe_k = 2 hparams.attent...
Base model with attention expert.
def attention_lm_moe_base_memeff(): """Base model with attention expert.""" hparams = attention_lm_moe_base_long_seq() hparams.use_sepconv = False hparams.diet_experts = True hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dropout = 0.0 hpa...
Cheap model for single-gpu training. on lm1b_32k: ~312M params 1.6 steps/sec on [GeForce GTX TITAN X] After 50K steps on 8 GPUs (synchronous): eval_log_ppl_per_token = 3.31 Returns: an hparams object.
def attention_lm_moe_small(): """Cheap model for single-gpu training. on lm1b_32k: ~312M params 1.6 steps/sec on [GeForce GTX TITAN X] After 50K steps on 8 GPUs (synchronous): eval_log_ppl_per_token = 3.31 Returns: an hparams object. """ hparams = attention_lm_moe_base() hparam...
Cheap model for debugging. Returns: an hparams object.
def attention_lm_attention_moe_tiny(): """Cheap model for debugging. Returns: an hparams object. """ hparams = attention_lm_moe_small() hparams.moe_layers = "" hparams.attention_num_experts = 128 hparams.filter_size = 8192 hparams.attention_type = AttentionType.LOCAL_EXPERTS return hparams
Large model for distributed training. Over 1B parameters, so requires multi-gpu training due to memory requirements. on lm1b_32k: After 45K steps on 8 GPUs (synchronous): eval_log_ppl_per_token = 3.18 eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_token) = 33.9 Returns: an hpar...
def attention_lm_moe_large(): """Large model for distributed training. Over 1B parameters, so requires multi-gpu training due to memory requirements. on lm1b_32k: After 45K steps on 8 GPUs (synchronous): eval_log_ppl_per_token = 3.18 eval_ppl_per_word = exp(1.107893 * eval_log_ppl_per_to...
Memory-efficient version.
def attention_lm_moe_memory_efficient(): """Memory-efficient version.""" hparams = attention_lm_moe_large() hparams.diet_experts = True hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.layer_prepostprocess_dropout = 0.0 hparams.memory_efficient_ffn = True hparams...
Unnecessarily large model with 24B params - because we can.
def attention_lm_moe_24b_diet(): """Unnecessarily large model with 24B params - because we can.""" hparams = attention_lm_moe_large_diet() hparams.moe_hidden_sizes = "12288" hparams.moe_num_experts = 1024 hparams.batch_size = 4096 return hparams
Version to use for seq2seq.
def attention_lm_moe_translation(): """Version to use for seq2seq.""" hparams = attention_lm_moe_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hparams....
Version to use with languagemodel_wiki_scramble1k50.
def attention_lm_moe_unscramble_base(): """Version to use with languagemodel_wiki_scramble1k50.""" hparams = attention_lm_no_moe_small() hparams.use_inputs = True hparams.min_length_bucket = 1024 hparams.max_length = 1024 hparams.batch_size = 5000 hparams.layer_prepostprocess_dropout = 0.0 hparams.layer...
Transform input from data space to model space. Args: x: A Tensor with shape [batch, ...] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: body_input: A Tensor with shape [batch, ?, ?, model_hparams.hidden_size].
def audio_bottom(x, model_hparams, vocab_size): """Transform input from data space to model space. Args: x: A Tensor with shape [batch, ...] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: body_input: A Tensor with shape [batch, ?, ?, model_hparams....
Bottom transformation for target images.
def image_targets_bottom(x, model_hparams, vocab_size): """Bottom transformation for target images.""" pixel_embedding_size = 64 inputs = x with tf.variable_scope("image_modality"): if not tf.executing_eagerly(): tf.summary.image( "targets_bottom", common_layers.tpu_safe_image_summ...
Compresses channel-wise input pixels into whole pixel representions. Perform conversion of RGB pixel values to a real number in the range -1 to 1. This combines pixel channels to form a representation of shape [img_len, img_len]. Args: inputs: Tensor representing RGB pixel intensities as integers, of shap...
def _image_channel_compress_bottom(inputs, model_hparams, name="bottom"): """Compresses channel-wise input pixels into whole pixel representions. Perform conversion of RGB pixel values to a real number in the range -1 to 1. This combines pixel channels to form a representation of shape [img_len, img_len]. A...
Bottom transformation for image targets.
def image_channel_embeddings_bottom(x, model_hparams, vocab_size): """Bottom transformation for image targets.""" del vocab_size # unused arg inputs = tf.to_int32(x) io_depth = model_hparams.num_channels tshape = common_layers.shape_list(inputs) hidden_size = model_hparams.hidden_size target_embeddings =...
Use batchnorm instead of CMVN and shorten the stft with strided convs. Args: x: float32 tensor with shape [batch_size, len, 1, freqs * channels] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: float32 tensor with shape [batch_size, shorter_len, 1, hidden_si...
def speech_recognition_bottom(x, model_hparams, vocab_size): """Use batchnorm instead of CMVN and shorten the stft with strided convs. Args: x: float32 tensor with shape [batch_size, len, 1, freqs * channels] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: ...
Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a list of num_shards Tensors.
def get_weights(model_hparams, vocab_size, hidden_dim=None): """Create or get concatenated embedding or softmax variable. Args: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. hidden_dim: dim of the variable. Defaults to _model_hparams' hidden_size Returns: a lis...
Bottom transformation for symbols.
def _symbol_bottom_simple(x, model_hparams, vocab_size, name, reuse): """Bottom transformation for symbols.""" with tf.variable_scope(name, reuse=reuse): # Ensure the inputs are 3-D if len(x.get_shape()) == 4: x = tf.squeeze(x, axis=3) while len(x.get_shape()) < 3: x = tf.expand_dims(x, axis...
Bottom transformation for target symbols.
def symbol_targets_bottom(x, model_hparams, vocab_size): """Bottom transformation for target symbols.""" if (model_hparams.shared_embedding_and_softmax_weights or model_hparams.get("shared_embedding")): try: return _symbol_bottom_simple( x, model_hparams, vocab_size, "shared", reuse=True) ...
Bottom transformation for embedding video bitwise.
def video_bitwise_bottom(x, model_hparams, vocab_size): """Bottom transformation for embedding video bitwise.""" pixel_embedding_size = 64 inputs = x with tf.variable_scope("video_modality_bitwise", reuse=tf.AUTO_REUSE): common_layers.summarize_video(inputs, "bottom") # Embed bitwise. assert vocab_s...
Bottom transformation for video.
def video_pixel_noise_bottom(x, model_hparams, vocab_size): """Bottom transformation for video.""" input_noise = getattr(model_hparams, "video_modality_input_noise", 0.25) inputs = x if model_hparams.mode == tf.estimator.ModeKeys.TRAIN: background = tfp.stats.percentile(inputs, 50., axis=[0, 1, 2, 3]) i...
Convert prediction and target from rgb to real.
def convert_rgb_to_real(prediction, targets): """Convert prediction and target from rgb to real.""" prediction = tf.squeeze(prediction, axis=-1) prediction = common_layers.convert_rgb_to_real(prediction) targets = common_layers.convert_rgb_to_real(targets) return prediction, targets
Compute the CTC loss.
def ctc_symbol_loss(top_out, targets, model_hparams, vocab_size, weight_fn): """Compute the CTC loss.""" del model_hparams, vocab_size # unused arg logits = top_out with tf.name_scope("ctc_loss", values=[logits, targets]): # For CTC we assume targets are 1d, [batch, length, 1, 1] here. targets_shape = ...
Compute loss numerator and denominator for one shard of output.
def generic_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = common_attention.maybe_upcast(logits, hparams=model_hparams) cutoff = getattr(model_hparams, "video_modality_l...
Average loss over the labels.
def multi_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Average loss over the labels.""" del vocab_size # unused arg logits = top_out num_labels = tf.shape(targets)[1] logits = tf.tile(logits, [1, num_labels, 1, 1, 1]) xent, weights = common_layers.padded_cross_entropy( log...
Apply softmax cross-entropy between outputs and targets. Args: top_out: logits Tensor with shape [batch, ?, ?, num_classes] targets: one-hot encoding Tensor with shape [batch, ?, ?, num_classes] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. weights_fn: Returns...
def one_hot_class_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Apply softmax cross-entropy between outputs and targets. Args: top_out: logits Tensor with shape [batch, ...
Poisson loss for real.
def real_log_poisson_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Poisson loss for real.""" del model_hparams, vocab_size # unused arg predictions = top_out if (len(common_layers.shape_l...
Loss for class label.
def sigmoid_class_label_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Loss for class label.""" # Expect inputs of size [batch-size, timesteps, 1, num-classes], where the # last d...
Compute loss numerator and denominator for one shard of output.
def video_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:]) targets = tf.reshape(targets, [-1] + common_laye...
Compute loss numerator and denominator for one shard of output.
def video_l1_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:-1]) targets = tf.reshape(targets, [-1] + common...
Compute loss numerator and denominator for one shard of output.
def video_l2_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = tf.reshape(logits, [-1] + common_layers.shape_list(logits)[2:-1]) targets = tf.reshape(targets, [-1] + common...
Transform inputs from model space to target space. Average over inner dims and a linear layer to logits. Args: body_output: A Tensor with shape [batch, ?, ?, body_output_size]. targets: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: a Tensors, each ...
def class_label_top(body_output, targets, model_hparams, vocab_size): """Transform inputs from model space to target space. Average over inner dims and a linear layer to logits. Args: body_output: A Tensor with shape [batch, ?, ?, body_output_size]. targets: model_hparams: HParams, model hyperparmet...
Top transformation for images.
def image_top(body_output, targets, model_hparams, vocab_size): """Top transformation for images.""" del targets # unused arg # TODO(lukaszkaiser): is this a universal enough way to get channels? num_channels = model_hparams.problem.num_channels with tf.variable_scope("rgb_softmax"): body_output_shape = ...
Transforms body output to return logits. Args: body_output: Tensor of shape [batch, img_len, img_len, depth]. targets: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: Tensor of shape [batch, img_len, img_len, channels, vocab_size].
def image_channel_compress_top(body_output, targets, model_hparams, vocab_size): """Transforms body output to return logits. Args: body_output: Tensor of shape [batch, img_len, img_len, depth]. targets: model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: ...
Top transformation for images.
def image_channel_embeddings_top(body_output, targets, model_hparams, vocab_size): """Top transformation for images.""" del targets # unused arg with tf.variable_scope("image_channel_embeddings_bottom"): img_le...
Loss for class label.
def softmax_last_timestep_class_label_top(body_output, targets, model_hparams, vocab_size): """Loss for class label.""" del targets # unused arg with tf.variable_scope( "softmax_las...
Loss for class label.
def softmax_max_pooling_class_label_top(body_output, targets, model_hparams, vocab_size): """Loss for class label.""" del targets # unused arg with tf.variable_scope( "softmax_max_pooling...
Generate logits. Args: body_output: A Tensor with shape [batch, p0, p1, model_hparams.hidden_size]. targets: Unused. model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: logits: A Tensor with shape [batch, p0, p1, ?, vocab_size].
def symbol_top(body_output, targets, model_hparams, vocab_size): """Generate logits. Args: body_output: A Tensor with shape [batch, p0, p1, model_hparams.hidden_size]. targets: Unused. model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: logits: A Te...
Top transformation for video.
def video_top(body_output, targets, model_hparams, vocab_size): """Top transformation for video.""" del targets # unused arg num_channels = model_hparams.problem.num_channels shape = common_layers.shape_list(body_output) reshape_shape = shape[:-1] + [num_channels, vocab_size] res = tf.reshape(body_output, ...
Top transformation for video.
def video_l1_top(body_output, targets, model_hparams, vocab_size): """Top transformation for video.""" del targets, vocab_size # unused arg num_channels = model_hparams.problem.num_channels num_frames = model_hparams.video_num_target_frames with tf.variable_scope("rgb"): body_output_shape = common_layers...
Gets default bottom transformation; if none available, return value.
def get_bottom(modality_type, value=None): """Gets default bottom transformation; if none available, return value.""" if modality_type == ModalityType.AUDIO: return audio_bottom elif modality_type == ModalityType.AUDIO_SPECTRAL: return audio_spectral_bottom elif modality_type in (ModalityType.CLASS_LABE...
Gets default loss transformation; if none available, return value.
def get_loss(modality_type, value=None): """Gets default loss transformation; if none available, return value.""" if modality_type in (ModalityType.AUDIO, ModalityType.AUDIO_SPECTRAL, ModalityType.CLASS_LABEL, ModalityType.IDENTITY, ...
Gets default name for transformations; if none available, return value.
def get_name(modality_type, value=None): """Gets default name for transformations; if none available, return value.""" # For legacy reasons, modalities vary in their naming scheme. Future plans are # to remove any need for get_name. We do not recommend using it. if modality_type == ModalityType.AUDIO: retur...
Gets default bottom transformation for targets; if none, return value.
def get_targets_bottom(modality_type, value=None): """Gets default bottom transformation for targets; if none, return value.""" if modality_type == ModalityType.AUDIO: return make_targets_bottom(audio_bottom) elif modality_type == ModalityType.AUDIO_SPECTRAL: return make_targets_bottom(audio_spectral_bott...
Gets default top transformation; if none available, return value.
def get_top(modality_type, value=None): """Gets default top transformation; if none available, return value.""" if modality_type in (ModalityType.AUDIO, ModalityType.AUDIO_SPECTRAL, ModalityType.GENERIC_L2_LOSS, ModalityType.IDENTITY, ...
Gets default weights function; if none available, return value.
def get_weights_fn(modality_type, value=None): """Gets default weights function; if none available, return value.""" if modality_type in (ModalityType.CTC_SYMBOL, ModalityType.IDENTITY_SYMBOL, ModalityType.MULTI_LABEL, ModalityType.SYMBOL, ...
Generates all possible pair combinations for the input list of sentences. For example: input = ["paraphrase1", "paraphrase2", "paraphrase3"] output = [("paraphrase1", "paraphrase2"), ("paraphrase1", "paraphrase3"), ("paraphrase2", "paraphrase3")] Args: list_of_sentences: the list...
def create_combination(list_of_sentences): """Generates all possible pair combinations for the input list of sentences. For example: input = ["paraphrase1", "paraphrase2", "paraphrase3"] output = [("paraphrase1", "paraphrase2"), ("paraphrase1", "paraphrase3"), ("paraphrase2", "paraphr...
Set of hyperparameters.
def image_transformer2d_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hparams.batch_size = 1 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams....
hparams fo 8 layer big 2d model for cifar 10.
def imagetransformer2d_base_8l_8_32_big(): """hparams fo 8 layer big 2d model for cifar 10.""" hparams = image_transformer2d_base() hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 2048 hparams.num_decoder_layers = 8 hparams.batch_size = 1 hparams.layer_prepostprocess_dropout = 0....
big 1d model for unconditional generation on imagenet.
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64_2d(): """big 1d model for unconditional generation on imagenet.""" hparams = image_transformer2d_base() hparams.unconditional = True hparams.hidden_size = 512 hparams.batch_size = 1 hparams.img_len = 64 hparams.num_heads = 8 hparams.filter_size = 2...
Base params for img2img 2d attention.
def img2img_transformer2d_base(): """Base params for img2img 2d attention.""" hparams = image_transformer2d_base() # learning related flags hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" # This version seems to benefit from a higher learning rate. hparams.learning_rate =...
Current best hparams for local 2d.
def img2img_transformer2d_q3(): """Current best hparams for local 2d.""" hparams = img2img_transformer2d_q1() hparams.batch_size = 2 hparams.query_shape = (8, 16) hparams.memory_flange = (8, 32) return hparams
Base params for local1d attention.
def img2img_transformer_base(): """Base params for local1d attention.""" hparams = image_transformer2d_base() # learning related flags hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" # This version seems to benefit from a higher learning rate. hparams.learning_rate = 0.2 ...
Current best hparams for local 1d.
def img2img_transformer_b3(): """Current best hparams for local 1d.""" hparams = img2img_transformer_base() hparams.batch_size = 2 hparams.layer_preprocess_sequence = "none" hparams.layer_postprocess_sequence = "dan" hparams.block_length = 128 hparams.sampling_temp = 0.9 return hparams
Try dilated.
def img2img_transformer_dilated(): """Try dilated.""" hparams = img2img_transformer_base() hparams.add_hparam("num_memory_blocks", 1) hparams.num_heads = 8 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_decoder_layer...
Hparams for training img2img_transformer on tpu.
def img2img_transformer_base_tpu(): """Hparams for training img2img_transformer on tpu.""" hparams = img2img_transformer_base() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 8 hparams.num_encoder_layers = 4 hparam...
Set of hyperparameters.
def img2img_transformer2d_n31(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.num_encoder_layers = 6 hparams.num_decoder_layers = 12 hparams.num_heads = 8 hparams.query_shape = (16, 32) hparams.memory_flange = (16, 32) return hparams
Set of hyperparameters.
def img2img_transformer2d_n24(): """Set of hyperparameters.""" hparams = img2img_transformer2d_base() hparams.batch_size = 1 hparams.hidden_size = 1024 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout = 0.2 hparams.num_decoder_layers = 8 hparams.query_shape = (8, 16) hparams.memory_flan...
Tiny params.
def img2img_transformer2d_tiny(): """Tiny params.""" hparams = img2img_transformer2d_base() hparams.num_decoder_layers = 2 hparams.hidden_size = 128 hparams.batch_size = 4 hparams.max_length = 128 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.filter_size = 128 hparams.n...
Tiny params.
def img2img_transformer_tiny(): """Tiny params.""" hparams = img2img_transformer2d_base() hparams.num_hidden_layers = 2 hparams.hidden_size = 128 hparams.batch_size = 4 hparams.max_length = 128 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.filter_size = 128 hparams.num_...
Residual feed-forward layer with normalization at start.
def ResidualFeedForward(feature_depth, feedforward_depth, dropout, mode): """Residual feed-forward layer with normalization at start.""" return layers.Residual( layers.LayerNorm(), layers.Dense(feedforward_depth), layers.Relu(...
Transformer encoder layer. The input to the encoder is a pair (embedded source, mask) where the mask is created from the original source to prevent attending to the padding part of the input. Args: feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_head...
def EncoderLayer(feature_depth, feedforward_depth, num_heads, dropout, mode): """Transformer encoder layer. The input to the encoder is a pair (embedded source, mask) where the mask is created from the original source to prevent attending to t...
Transformer encoder. Args: vocab_size: int: vocab size num_classes: how many classes on output feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_layers: int: number of encoder/decoder layers num_heads: int: number of attention heads dropout: f...
def TransformerEncoder(vocab_size, num_classes=10, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, max_len=2048, ...
Transformer decoder layer. Args: feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_heads: int: number of attention heads dropout: float: dropout rate (how much to drop out) mode: str: 'train' or 'eval' Returns: the layer.
def DecoderLayer(feature_depth, feedforward_depth, num_heads, dropout, mode): """Transformer decoder layer. Args: feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_heads: int: number of att...
Transformer language model (only uses the decoder part of Transformer). Args: vocab_size: int: vocab size feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_layers: int: number of encoder/decoder layers num_heads: int: number of attention heads dro...
def TransformerLM(vocab_size, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, max_len=2048, mode='train'): """Transformer language model (only uses the decod...
Transformer decoder layer operating on chunks. Args: feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_heads: int: number of attention heads dropout: float: dropout rate (how much to drop out) chunk_selector: a function from chunk number to list of ch...
def ChunkedDecoderLayer(feature_depth, feedforward_depth, num_heads, dropout, chunk_selector, mode): """Transformer decoder layer operating on chunks. Args: feature_depth: int: depth of embe...
Transformer language model operating on chunks. The input to this model is a sequence presented as a list or tuple of chunks: (chunk1, chunk2, chunks3, ..., chunkN). Each chunk should have the same shape (batch, chunk-length) and together they represent a long sequence that's a concatenation chunk1,chunk2,....
def ChunkedTransformerLM(vocab_size, feature_depth=512, feedforward_depth=2048, num_layers=6, num_heads=8, dropout=0.1, chunk_selector=None, max_...
Transformer model. Args: source_vocab_size: int: source vocab size target_vocab_size: int: target vocab size mode: str: 'train' or 'eval' num_layers: int: number of encoder/decoder layers feature_depth: int: depth of embedding feedforward_depth: int: depth of feed-forward layer num_heads...
def Transformer(source_vocab_size, target_vocab_size, mode='train', num_layers=6, feature_depth=512, feedforward_depth=2048, num_heads=8, dropout=0.1, shared_embedding=True, ma...
Catch bugs locally...
def mtf_transformer_tiny(): """Catch bugs locally...""" hparams = mtf_transformer_base() hparams.d_model = 128 hparams.d_ff = 512 hparams.batch_size = 8 hparams.encoder_layers = ["att", "drd"] * 2 hparams.decoder_layers = ["att", "enc_att", "drd"] * 2 hparams.num_heads = 8 # data parallelism and model...
Config for language-model experiments. Train these on languagemodel_lm1b32k_packed for 136000 steps (10 epochs) The size parameter is an integer that controls the number of heads and the size of the size of the feedforward hidden layers. Increasing size by 1 doubles each of these. Results: size params...
def mtf_transformer_paper_lm(size): """Config for language-model experiments. Train these on languagemodel_lm1b32k_packed for 136000 steps (10 epochs) The size parameter is an integer that controls the number of heads and the size of the size of the feedforward hidden layers. Increasing size by 1 doubles e...
Config for translation experiments. Train these on translate_enfr_wmt32k_packed for 154000 steps (3 epochs) The size parameter is an integer that controls the number of heads and the size of the size of the feedforward hidden layers. Increasing size by 1 doubles each of these. Args: size: an integer ...
def mtf_transformer_paper_tr(size): """Config for translation experiments. Train these on translate_enfr_wmt32k_packed for 154000 steps (3 epochs) The size parameter is an integer that controls the number of heads and the size of the size of the feedforward hidden layers. Increasing size by 1 doubles each ...
Small language model to run on 1 TPU. Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs) Results: params/10^9 log-ppl(per-token) 0.14 3.202 Returns: a hparams
def mtf_transformer_lm_baseline(): """Small language model to run on 1 TPU. Run this on 2x2 on languagemodel_lm1b32k_packed for 272000 steps (10 epochs) Results: params/10^9 log-ppl(per-token) 0.14 3.202 Returns: a hparams """ hparams = mtf_transformer_paper_lm(-1) hparams...
Multihead scaled-dot-product attention with input/output transformations. Args: query_antecedent: a Tensor with shape [batch, length_q, channels] memory_antecedent: a Tensor with shape [batch, length_m, channels] or None bias: bias Tensor (see attention_bias()) total_key_depth: an integer total_v...
def multihead_graph_attention(query_antecedent, memory_antecedent, bias, total_key_depth, total_value_depth, output_depth, num_heads, ...
graph attention. Args: q: a Tensor with shape [batch, heads, length_q, depth_k] k: a Tensor with shape [batch, heads, length_kv, depth_k] v: a Tensor with shape [batch, heads, length_kv, depth_v] bias: bias Tensor (see attention_bias()) dropout_rate: a floating point number image_shapes: opti...
def graph_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, save_weights_to=None, dropout_br...
Helper function that computes transformation for keys and values. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let V be the size of the attention values (total_value_d...
def _compute_edge_transforms(node_states, depth, num_transforms, name="transform"): """Helper function that computes transformation for keys and values. Let B be the number of batches. Let N be the number of nodes in the graph...
Computes query, key and value for edge matrices. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let V be the size of the attention values (total_value_depth). Let T be...
def compute_mpnn_qkv(node_states, total_key_depth, total_value_depth, num_transforms): """Computes query, key and value for edge matrices. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidd...
Identical to sparse_ggnn except that each input has a batch dimension. B = The batch size. N = The number of nodes in each batch. H = The size of the hidden states. T = The number of edge types. Args: node_states: Initial states of each node in the graph. Shape: [B, N, H] adjacency_matrices: Adjacen...
def sparse_message_pass_batched(node_states, adjacency_matrices, num_edge_types, hidden_size, use_bias=True, average_aggregation=False, ...
One message-passing step for a GNN with a sparse adjacency matrix. Implements equation 2 (the message passing step) in [Li et al. 2015](https://arxiv.org/abs/1511.05493). N = The number of nodes in each batch. H = The size of the hidden states. T = The number of edge types. Args: node_states: Initial...
def sparse_message_pass(node_states, adjacency_matrices, num_edge_types, hidden_size, use_bias=True, average_aggregation=False, name="sparse_ggnn"): """One message-passing st...
Multihead scaled-dot-product attention with input/output transformations. Let B be the number of batches. Let N be the number of nodes in the graph. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries (total_key_depth). Let V be the size of the attention values (total...
def multihead_mpnn_attention(node_states, total_key_depth, total_value_depth, output_depth, num_heads, adjacency_matrix=None, num_edge_types=5, ...
Dot product attention with edge vectors. Let B be the number of batches. Let N be the number of nodes in the graph. Let K be the size of the attention keys/queries. Let V be the size of the attention values. Let T be the total number of transforms (num_transforms). Args: q: The query Tensor of shape [...
def dot_product_mpnn_attention(q, k, v, adjacency_matrix, num_edge_types, num_transforms=None, use_weighted_sum=False, ...
ggnn version of the MPNN from Gilmer et al. Let B be the number of batches. Let D be the size of the node hidden states. Let K be the size of the attention keys/queries. Let V be the size of the output of the ggnn. Let T be the number of transforms / edge types. Args: node_states: The value Tensor of ...
def ggnn_fast_dense(node_states, adjacency_matrix, num_edge_types, total_value_depth, name=None): """ggnn version of the MPNN from Gilmer et al. Let B be the number of batches. Let D be the size of the node hidden states. Let K be ...
Compute values. If edge compatibilities is just adjacency, we get ggnn. Args: edge_compatibility: A tensor of shape [batch, num_transforms, length, depth] v: A tensor of shape [batch, num_transforms, length, depth] Returns: output: A [batch, length, depth] tensor
def compute_values(edge_compatibility, v): """Compute values. If edge compatibilities is just adjacency, we get ggnn. Args: edge_compatibility: A tensor of shape [batch, num_transforms, length, depth] v: A tensor of shape [batch, num_transforms, length, depth] Returns: output: A [batch, length, dept...
Precompute the a_in and a_out tensors. (we don't want to add to the graph everytime _fprop is called) Args: adjacency: placeholder of real valued vectors of shape [B, L, L, E] hparams: HParams object Returns: edge_matrices: [batch, L * D, L * D] the dense matrix for message passing viewed as a bl...
def precompute_edge_matrices(adjacency, hparams): """Precompute the a_in and a_out tensors. (we don't want to add to the graph everytime _fprop is called) Args: adjacency: placeholder of real valued vectors of shape [B, L, L, E] hparams: HParams object Returns: edge_matrices: [batch, L * D, L * D] ...
Computes a_t from h_{t-1}, see bottom of page 3 in the paper. Args: node_states: [B, L, D] tensor (h_{t-1}) edge_matrices (tf.float32): [B, L*D, L*D] Returns: messages (tf.float32): [B, L, D] For each pair of nodes in the graph a message is sent along both the incoming and outgoing edge.
def dense_message_pass(node_states, edge_matrices): """Computes a_t from h_{t-1}, see bottom of page 3 in the paper. Args: node_states: [B, L, D] tensor (h_{t-1}) edge_matrices (tf.float32): [B, L*D, L*D] Returns: messages (tf.float32): [B, L, D] For each pair of nodes in the graph a message i...
Helper: build tf.Example from (string -> int/float/str list) dictionary.
def to_example(dictionary): """Helper: build tf.Example from (string -> int/float/str list) dictionary.""" features = {} for (k, v) in six.iteritems(dictionary): if not v: raise ValueError("Empty generated field: %s" % str((k, v))) if isinstance(v[0], six.integer_types): features[k] = tf.train...
generate_files but with a single writer writing to shard task_id.
def generate_files_distributed(generator, output_name, output_dir, num_shards=1, max_cases=None, task_id=0): """generate_files but with a single writer writing to ...
Generate cases from a generator and save as TFRecord files. Generated cases are transformed to tf.Example protos and saved as TFRecords in sharded files named output_dir/output_name-00..N-of-00..M=num_shards. Args: generator: a generator yielding (string -> int/float/str list) dictionaries. output_filen...
def generate_files(generator, output_filenames, max_cases=None, cycle_every_n=1): """Generate cases from a generator and save as TFRecord files. Generated cases are transformed to tf.Example protos and saved as TFRecords in sharded files named output_dir/output_name-00..N-of-00..M=num_shards. ...
Report hook for download progress. Args: count: current block number block_size: block size total_size: total size
def download_report_hook(count, block_size, total_size): """Report hook for download progress. Args: count: current block number block_size: block size total_size: total size """ percent = int(count * block_size * 100 / total_size) print("\r%d%%" % percent + " completed", end="\r")