INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Cycle GAN, main step used for training.
def cycle_gan_internal(inputs, targets, _, hparams): """Cycle GAN, main step used for training.""" with tf.variable_scope("cycle_gan"): # Embed inputs and targets. inputs_orig, targets_orig = tf.to_int32(inputs), tf.to_int32(targets) inputs = common_layers.embedding( inputs_orig, hparams.vocab_s...
Hparams for decoding.
def decode_hparams(overrides=""): """Hparams for decoding.""" hparams = decoding.decode_hparams() # Number of interpolations between [0.0, 1.0]. hparams.add_hparam("num_interp", 11) # Which level(s) to interpolate. hparams.add_hparam("level_interp", [0, 1, 2]) # "all" or "ranked", interpolate all channels...
Set of hyperparameters.
def cycle_gan_small(): """Set of hyperparameters.""" hparams = transformer_vae.transformer_ae_small() hparams.batch_size = 2048 hparams.bottom = { "inputs": modalities.identity_bottom, "targets": modalities.identity_bottom, } hparams.top = { "targets": modalities.identity_top, } hparam...
Preprocess frame. 1. Converts [0, 255] to [-0.5, 0.5] 2. Adds uniform noise. Args: frame: 3-D Tensor representing pixels. Returns: frame: 3-D Tensor with values in between [-0.5, 0.5]
def preprocess_frame(frame): """Preprocess frame. 1. Converts [0, 255] to [-0.5, 0.5] 2. Adds uniform noise. Args: frame: 3-D Tensor representing pixels. Returns: frame: 3-D Tensor with values in between [-0.5, 0.5] """ # Normalize from [0.0, 1.0] -> [-0.5, 0.5] frame = common_layers.convert_r...
Encode frames to latents.
def frame_to_latents(frame, hparams): """Encode frames to latents.""" # Preprocess frame = preprocess_frame(frame) # Encode [X_t] to [z^1_t, z^2_t .. z^l_t] glow_vals = glow_ops.encoder_decoder( "codec", frame, hparams, eps=None, reverse=False) z_top, _, level_eps, _, _ = glow_vals return z_top, le...
Decodes latents to frames.
def latents_to_frames(z_top_interp, level_eps_interp, hparams): """Decodes latents to frames.""" # Decode [z^1_t, z^2_t .. z^l_t] to [X_t] images, _, _, _ = glow_ops.encoder_decoder( "codec", z_top_interp, hparams, eps=level_eps_interp, reverse=True) images = glow_ops.postprocess(images) return images
Interpolate between the first input frame and last target frame. Args: features: dict of tensors hparams: HParams, training hparams. decode_hp: HParams, decode hparams. Returns: images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C) first_frame: image, 3-D Tensor, shape=(1, H, W, ...
def interpolate(features, hparams, decode_hp): """Interpolate between the first input frame and last target frame. Args: features: dict of tensors hparams: HParams, training hparams. decode_hp: HParams, decode hparams. Returns: images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C) ...
Get nested summaries_log_dir based on decode_hp.
def get_summaries_log_dir(decode_hp, output_dir, dataset_split): """Get nested summaries_log_dir based on decode_hp.""" child_dir = decode_hp.summaries_log_dir level_dir = "".join([str(level) for level in decode_hp.level_interp]) if decode_hp.channel_interp == "all": rank_dir = "all" else: rank_dir = ...
Converts interpolated frames into tf summaries. The summaries consists of: 1. Image summary corresponding to the first frame. 2. Image summary corresponding to the last frame. 3. The interpolated frames as a gif summary. Args: sample_ind: int interpolations: Numpy array, shape=(num_interp, H, ...
def interpolations_to_summary(sample_ind, interpolations, first_frame, last_frame, hparams, decode_hp): """Converts interpolated frames into tf summaries. The summaries consists of: 1. Image summary corresponding to the first frame. 2. Image summary corresponding to the last f...
EPVA hparams.
def next_frame_epva(): """EPVA hparams.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.bottom = { "inputs": modalities.video_raw_bottom, "targets": modalities.video_raw_targets_bottom, } hp...
Create slot variables for Adam with accumulated gradients.
def _create_slots(self, var_list): """Create slot variables for Adam with accumulated gradients.""" super(MultistepAdamOptimizer, self)._create_slots(var_list) first_var = min(var_list, key=lambda x: x.name) self._create_non_slot_variable(initial_value=0 if self._n == 1 else 1, ...
Apply conditionally if counter is zero.
def _apply_cond(self, apply_fn, grad, var, *args, **kwargs): """Apply conditionally if counter is zero.""" grad_acc = self.get_slot(var, "grad_acc") def apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs): total_grad = (grad_acc + grad) / tf.cast(self._n_t, grad.dtype) adam_op = apply_fn...
Updates beta_power variables every n batches and incrs counter.
def _finish(self, update_ops, name_scope): """Updates beta_power variables every n batches and incrs counter.""" iter_ = self._get_iter_variable() beta1_power, beta2_power = self._get_beta_accumulators() with tf.control_dependencies(update_ops): with tf.colocate_with(iter_): def update_be...
A stack of transformer layers. 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 Returns: y: a Tensors
def transformer_revnet_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder"): """A stack of transformer layers. Args: encoder_input: a Tensor encoder_self_attention_bias: bias Tensor for self...
A stack of transformer layers. Args: decoder_input: a Tensor encoder_output: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention (see common_attention.attenti...
def transformer_revnet_decoder(decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, name="decoder"): """A stack of ...
Base hparams for TransformerRevnet.
def transformer_revnet_base(): """Base hparams for TransformerRevnet.""" hparams = transformer.transformer_big() # Use settings from transformer_n_da hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 return hparams
Base hparams for TransformerRevnet.
def transformer_revnet_big(): """Base hparams for TransformerRevnet.""" hparams = transformer_revnet_base() # The TransformerRevnet uses significantly less memory than the Transformer. # Increase batch size and model size. hparams.batch_size *= 2 hparams.hidden_size *= 2 hparams.num_heads *= 2 hparams....
Over which devices do we split each training batch. In old-fashioned async mode, we split the batch over all GPUs on the current worker. In sync mode, we split the batch over all the parameter server GPUs. This function returns an expert_utils.Parallelism object, which can be used to build the model. It i...
def data_parallelism_from_flags(daisy_chain_variables=True, all_workers=False): """Over which devices do we split each training batch. In old-fashioned async mode, we split the batch over all GPUs on the current worker. In sync mode, we split the batch over all the parameter server GPUs. This function retu...
See data_parallelism_from_flags.
def data_parallelism(daisy_chain_variables=True, all_workers=False, ps_replicas=0, ps_job="/job:ps", ps_gpu=0, schedule="continuous_train_and_eval", sync=False, worker_gpu=1...
Generate concatenated lines from file upto up_threshold characters.
def concat_generator(filename, up_threshold, low_threshold=10): """Generate concatenated lines from file upto up_threshold characters.""" txt = "" for line in tf.gfile.Open(filename): line = line.strip() if len(txt) + len(line) + 1 >= up_threshold: ret = txt txt = "" # We don't yield ver...
Given python generators, generate from one, then from another, etc.
def mix_generators(generator_list): """Given python generators, generate from one, then from another, etc.""" i = 0 l = len(generator_list) stopiters_seen = 0 while stopiters_seen <= l: try: yield six.next(generator_list[i % l]) i += 1 stopiters_seen = 0 except StopIteration: i...
Compute BLEU core summaries using the decoder output. Args: hook_args: DecodeHookArgs namedtuple Returns: A list of tf.Summary values if hook_args.hparams contains the reference file and the translated file.
def compute_bleu_summaries(hook_args): """Compute BLEU core summaries using the decoder output. Args: hook_args: DecodeHookArgs namedtuple Returns: A list of tf.Summary values if hook_args.hparams contains the reference file and the translated file. """ decode_hparams = hook_args.decode_hparams ...
Preprocessing to strip tags in SGM files.
def _preprocess_sgm(line, is_sgm): """Preprocessing to strip tags in SGM files.""" if not is_sgm: return line # In SGM files, remove <srcset ...>, <p>, <doc ...> lines. if line.startswith("<srcset") or line.startswith("</srcset"): return "" if line.startswith("<doc") or line.startswith("</doc"): r...
Concatenates all `datasets` and saves to `filename`.
def compile_data(tmp_dir, datasets, filename, datatypes_to_clean=None): """Concatenates all `datasets` and saves to `filename`.""" datatypes_to_clean = datatypes_to_clean or [] filename = os.path.join(tmp_dir, filename) lang1_fname = filename + ".lang1" lang2_fname = filename + ".lang2" if tf.gfile.Exists(l...
Get vocab for distill problems.
def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False): """Get vocab for distill problems.""" # We assume that vocab file is present in data_dir directory where the # data generated will be stored. vocab_filepath = os.path.join(data_dir, self.vocab_filename) encoder = text_encoder.Subword...
Set hparams overrides from unparsed args list.
def set_hparams_from_args(args): """Set hparams overrides from unparsed args list.""" if not args: return hp_prefix = "--hp_" tf.logging.info("Found unparsed command-line arguments. Checking if any " "start with %s and interpreting those as hparams " "settings.", hp_pref...
Create hparams.
def create_hparams(): """Create hparams.""" if FLAGS.use_tpu and "tpu" not in FLAGS.hparams_set: tf.logging.warn("Not all hyperparameter sets work on TPU. " "Prefer hparams_sets with a '_tpu' suffix, " "e.g. transformer_tpu, if available for your model.") hparams_path =...
Create a run config. Args: hp: model hyperparameters output_dir: model's output directory, defaults to output_dir flag. Returns: a run config
def create_run_config(hp, output_dir=None): """Create a run config. Args: hp: model hyperparameters output_dir: model's output directory, defaults to output_dir flag. Returns: a run config """ save_ckpt_steps = max(FLAGS.iterations_per_loop, FLAGS.local_eval_frequency) save_ckpt_secs = FLAGS.s...
Saves FLAGS and hparams to output_dir.
def save_metadata(hparams): """Saves FLAGS and hparams to output_dir.""" output_dir = os.path.expanduser(FLAGS.output_dir) if not tf.gfile.Exists(output_dir): tf.gfile.MakeDirs(output_dir) # Save FLAGS in txt file if hasattr(FLAGS, "flags_into_string"): flags_str = FLAGS.flags_into_string() t2t_f...
A stack of convolution blocks with residual connection.
def residual_block(x, hparams): """A stack of convolution blocks with residual connection.""" k = (hparams.kernel_height, hparams.kernel_width) dilations_and_kernels = [((1, 1), k) for _ in range(3)] y = common_layers.subseparable_conv_block( x, hparams.hidden_size, dilations_and_kernels, ...
Xception body.
def xception_internal(inputs, hparams): """Xception body.""" with tf.variable_scope("xception"): cur = inputs if cur.get_shape().as_list()[1] > 200: # Large image, Xception entry flow cur = xception_entry(cur, hparams.hidden_size) else: # Small image, conv cur = common_layers.co...
Xception entry flow.
def xception_entry(inputs, hidden_dim): """Xception entry flow.""" with tf.variable_scope("xception_entry"): def xnet_resblock(x, filters, res_relu, name): """Resblock.""" with tf.variable_scope(name): y = common_layers.separable_conv_block( x, filters, [((1, 1), (3,...
Xception exit flow.
def xception_exit(inputs): """Xception exit flow.""" with tf.variable_scope("xception_exit"): x = inputs x_shape = x.get_shape().as_list() if x_shape[1] is None or x_shape[2] is None: length_float = tf.to_float(tf.shape(x)[1]) length_float *= tf.to_float(tf.shape(x)[2]) spatial_dim_flo...
Returns a plaintext representation of HTML content.
def get_text_from_html(html): """Returns a plaintext representation of HTML content.""" try: soup = bs4.BeautifulSoup(html, "html.parser") except: # pylint: disable=bare-except # Some docs don't parse return "" # Remove script and style tags for s in soup(["script", "style"]): s.decompose() ...
Return text strings in soup.
def _soup_strings(soup): """Return text strings in soup.""" paragraph_tags = set([ "caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td", "div", "span" ]) skip_children = None for descendant in soup.descendants: # If we've treated a tag as a contiguous paragraph, don't re-...
Set of hyperparameters.
def image_transformer_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hparams.batch_size = 4 hparams.max_length = 3075 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e-9 hparams.l...
Best config for 2.90 bits/dim on CIFAR10 using cross entropy.
def imagetransformer_cifar10_base(): """Best config for 2.90 bits/dim on CIFAR10 using cross entropy.""" hparams = image_transformer_base() hparams.batch_size = 4 hparams.num_heads = 4 hparams.num_decoder_layers = 12 hparams.block_length = 256 hparams.hidden_size = 512 hparams.filter_size = 2048 hpara...
Best config for 2.90 bits/dim on CIFAR10 using DMOL.
def imagetransformer_cifar10_base_dmol(): """Best config for 2.90 bits/dim on CIFAR10 using DMOL.""" hparams = image_transformer_base() hparams.likelihood = cia.DistributionType.DMOL hparams.num_channels = 1 hparams.bottom["targets"] = modalities.image_channel_compress_targets_bottom hparams.top["targets"] ...
Transformer base params for cifar-10.
def imagetransformer_base_tpu(): """Transformer base params for cifar-10.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.block_length = 128 ...
Transformer base params for cifar-10.
def imagetransformer_base_imagenet_tpu(): """Transformer base params for cifar-10.""" hparams = imagetransformer_base_tpu() hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.block_length = 128 hparams.layer_preprocess_sequence = "none" hp...
separate rgb embeddings.
def imagetransformer_sep_channels(): """separate rgb embeddings.""" hparams = imagetransformer_base() hparams.num_heads = 4 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 256 hparams.filter_size = 512 hparams.num_hidden_layers = 6 return hparams
separate rgb embeddings.
def imagetransformer_sep_channels_8l(): """separate rgb embeddings.""" hparams = imagetransformer_base() hparams.num_heads = 4 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 256 hparams.filter_size = 256 hparams.num_hidden_layers = 8 hparams.sampling_method =...
big 1d model for conditional image generation.2.99 on cifar10.
def imagetransformer_base_8l_8h_big_cond_dr03_dan(): """big 1d model for conditional image generation.2.99 on cifar10.""" hparams = imagetransformer_sep_channels_8l() hparams.block_width = 256 hparams.block_length = 256 hparams.hidden_size = 512 hparams.num_heads = 8 hparams.filter_size = 2048 hparams.b...
big 1d model for unconditional generation on imagenet.
def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64(): """big 1d model for unconditional generation on imagenet.""" hparams = imagetransformer_base_10l_8h_big_cond_dr03_dan() hparams.unconditional = True hparams.max_length = 14000 hparams.batch_size = 1 hparams.img_len = 64 hparams.layer_prepostproces...
separate rgb embeddings.
def imagetransformerpp_sep_channels_8l_8h(): """separate rgb embeddings.""" hparams = imagetransformer_base() hparams.likelihood = cia.DistributionType.DMOL hparams.num_channels = 1 hparams.bottom["targets"] = modalities.image_channel_compress_targets_bottom hparams.top["targets"] = modalities.identity_top ...
big 1d model for conditional image generation.2.99 on cifar10.
def imagetransformerpp_base_8l_8h_big_cond_dr03_dan(): """big 1d model for conditional image generation.2.99 on cifar10.""" hparams = imagetransformerpp_sep_channels_8l_8h() hparams.hidden_size = 512 hparams.num_heads = 8 hparams.filter_size = 2048 hparams.batch_size = 4 hparams.max_length = 3075 hparam...
Gets to 2.92 in just under 4 days on 8 p100s.
def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p(): """Gets to 2.92 in just under 4 days on 8 p100s.""" hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l() hparams.num_decoder_layers = 14 hparams.batch_size = 8 hparams.layer_prepostprocess_dropout = 0.2 return hparams
For 256x256.
def imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1(): """For 256x256.""" hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g() # TODO(trandustin): I forgot to set this in the runs! Maybe it's not used in # image transformer training implementation? # hparams.img_len = 256 hparams.max_len...
Dilated hparams.
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated(): """Dilated hparams.""" hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan() hparams.gap_sizes = [0, 16, 64, 0, 16, 64, 128, 0] hparams.dec_attention_type = cia.AttentionType.DILATED hparams.block_length = 128 hparams.block_width = 128 hpara...
big 1d model for conditional image generation.
def imagetransformer_base_12l_8h_big(): """big 1d model for conditional image generation.""" hparams = imagetransformer_sep_channels_8l_8h() hparams.filter_size = 1024 hparams.num_decoder_layers = 12 hparams.batch_size = 1 hparams.hidden_size = 512 hparams.learning_rate_warmup_steps = 4000 hparams.sampl...
hparams fo 12 layer big 1d model for imagenet 64x64.
def imagetransformer1d_base_8l_64by64(): """hparams fo 12 layer big 1d model for imagenet 64x64.""" hparams = image_transformer_base() hparams.num_heads = 8 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_decoder_layers = 8 hparams.batch_size = 1 hparams.block_length = 512 hparams.blo...
separate rgb embeddings.
def imagetransformer_sep_channels_12l_16h_imagenet_large(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_8l_8h() hparams.num_hidden_layers = 12 hparams.batch_size = 1 hparams.filter_size = 2048 hparams.num_heads = 16 hparams.learning_rate_warmup_steps = 16000 hparams.sampling_m...
separate rgb embeddings.
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_12l_16h_imagenet_large() hparams.num_hidden_layers = 16 hparams.local_attention = True hparams.batch_size = 1 hparams.block_length = 256 return hparams
separate rgb embeddings.
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc_128(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_12l_16h_imagenet_large() hparams.num_hidden_layers = 16 hparams.local_attention = True hparams.batch_size = 1 hparams.block_length = 128 return hparams
big 1d model for conditional image generation.
def imagetransformer_base_10l_16h_big_uncond_dr01_imgnet(): """big 1d model for conditional image generation.""" hparams = imagetransformer_base_14l_8h_big_dr01() # num_hidden_layers hparams.num_decoder_layers = 10 hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.batc...
big 1d model for conditional image generation.
def imagetransformer_base_10l_16h_big_dr01_imgnet(): """big 1d model for conditional image generation.""" hparams = imagetransformer_base_14l_8h_big_dr01() # num_hidden_layers hparams.num_decoder_layers = 10 hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.batch_size ...
separate rgb embeddings.
def imagetransformer_sep_channels_8l_8h(): """separate rgb embeddings.""" hparams = imagetransformer_base() hparams.num_heads = 8 hparams.batch_size = 1 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 512 hparams.filter_size = 512 hparams.num_hidden_layers = 8...
big 1d model for conditional image generation.
def imagetransformer_bas8l_8h_big_uncond_dr03_imgnet(): """big 1d model for conditional image generation.""" hparams = imagetransformer_base_14l_8h_big_dr01() # num_hidden_layers hparams.num_decoder_layers = 8 hparams.num_heads = 8 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepo...
separate rgb embeddings.
def imagetransformer_sep_channels_8l_8h_local_and_global_att(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_8l_8h() hparams.num_heads = 8 hparams.batch_size = 1 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 256 hparams.filter_size = ...
big 1d model for conditional image generation.
def imagetransformer_base_10l_16h_big_dr01_moe_imgnet(): """big 1d model for conditional image generation.""" hparams = imagetransformer_base_10l_16h_big_dr01_imgnet() hparams.initializer = "orthogonal" hparams.learning_rate_warmup_steps = 16000 hparams.add_hparam("moe_layers_decoder", "2,7") # Which layer i...
Set of hyperparameters for a very small imagetransformer with MoE.
def imagetransformer_moe_tiny(): """Set of hyperparameters for a very small imagetransformer with MoE.""" hparams = imagetransformer_tiny() hparams.hidden_size = 64 hparams.batch_size = 1 hparams.num_hidden_layers = 3 hparams.dec_attention_type = cia.AttentionType.MOE_LOCAL_1D hparams.add_hparam("moe_laye...
Hparams for training imagetransformer on tpu.
def imagetransformer_sep_channels_8l_tpu(): """Hparams for training imagetransformer on tpu.""" hparams = imagetransformer_sep_channels_8l() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.shared_embedding_and_softmax_weights = False retu...
Small model for tpu cifar 10.
def imagetransformer_b10l_4h_big_uncond_dr03_tpu(): """Small model for tpu cifar 10.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 10 hparams.block_len...
Moe tpu params.
def imagetransformer_b10l_dr03_moe_tpu(): """Moe tpu params.""" hparams = imagetransformer_b10l_4h_big_uncond_dr03_tpu() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 10 hparams.layer_preprocess_sequence = "none" ...
TPU related small model.
def imagetransformer_b10l_4h_big_uncond_dr03_lr025_tpu(): """TPU related small model.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 10 hparams.learning...
works very well on 4x4.
def imagetransformer_b12l_4h_b256_uncond_dr03_tpu(): """works very well on 4x4.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.block_length =...
works very well on 4x4.
def imagetransformer_b12l_4h_b256_uncond_dr03_rel_tpu(): """works very well on 4x4.""" hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu() hparams.shared_rel = True hparams.dec_attention_type = cia.AttentionType.RELATIVE_LOCAL_1D return hparams
Range of hyperparameters for vizier.
def imagetransformer_cifar_tpu_range(rhp): """Range of hyperparameters for vizier.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16]) rhp.set_discrete("hidden_size", [256, ...
TPU related imagenet model.
def imagetransformer_b12l_4h_b128_h512_uncond_dr01_im(): """TPU related imagenet model.""" hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu() update_hparams_for_tpu(hparams) hparams.batch_size = 4 hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_w...
TPU related small model.
def imagetransformer_b12l_4h_uncond_dr03_tpu(): """TPU related small model.""" hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu() hparams.learning_rate = 0.2 hparams.learning_rate_warmup_steps = 4000 hparams.layer_preprocess_sequence = "none" hparams.layer_postprocess_sequence = "dan" hparams.layer...
TPU config for cifar 10.
def imagetransformer_b12l_4h_b128_uncond_dr03_tpu(): """TPU config for cifar 10.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 4 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.block_length ...
TPU related 12 layer 8 heads model.
def imagetransformer_b12l_8h_b256_uncond_dr03_tpu(): """TPU related 12 layer 8 heads model.""" hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet() update_hparams_for_tpu(hparams) hparams.batch_size = 2 hparams.num_heads = 8 # heads are expensive on tpu hparams.num_decoder_layers = 12 hparams.bl...
big 1d model for conditional image generation.
def imagetransformer_b10l_4h_big_uncond_dr01_tpu(): """big 1d model for conditional image generation.""" hparams = imagetransformer_b12l_4h_big_uncond_dr03_tpu() # num_hidden_layers hparams.num_decoder_layers = 10 hparams.num_heads = 4 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.batch_...
Context manager wrapping the training loop, updates step counters.
def training_loop(self): """Context manager wrapping the training loop, updates step counters.""" if not self.restarting: self._write_counters(self._local_step_at_start, self._global_step) tf.logging.info( "Training %s up to %d, %d to go", self.model_mode, self.target_local_step, self...
Reads words from a file.
def _read_words(filename): """Reads words from a file.""" with tf.gfile.GFile(filename, "r") as f: if sys.version_info[0] >= 3: return f.read().replace("\n", " %s " % EOS).split() else: return f.read().decode("utf-8").replace("\n", " %s " % EOS).split()
Reads a file to build a vocabulary of `vocab_size` most common words. The vocabulary is sorted by occurrence count and has one word per line. Originally from: https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py Args: filename: file to read list of words from. vocab_path: pa...
def _build_vocab(filename, vocab_path, vocab_size): """Reads a file to build a vocabulary of `vocab_size` most common words. The vocabulary is sorted by occurrence count and has one word per line. Originally from: https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py Args: file...
Reads from file and returns a `TokenTextEncoder` for the vocabulary.
def _get_token_encoder(vocab_dir, vocab_name, filename): """Reads from file and returns a `TokenTextEncoder` for the vocabulary.""" vocab_path = os.path.join(vocab_dir, vocab_name) if not tf.gfile.Exists(vocab_path): _build_vocab(filename, vocab_path, 10000) return text_encoder.TokenTextEncoder(vocab_path)
Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files.
def _maybe_download_corpus(tmp_dir, vocab_type): """Download and unpack the corpus. Args: tmp_dir: directory containing dataset. vocab_type: which vocabulary are we using. Returns: The list of names of files. """ filename = os.path.basename(PTB_URL) compressed_filepath = generator_utils.maybe_...
Normalize attention matrices and reshape as necessary.
def resize(att_mat, max_length=None): """Normalize attention matrices and reshape as necessary.""" for i, att in enumerate(att_mat): # Add extra batch dim for viz code to work. if att.ndim == 3: att = np.expand_dims(att, axis=0) if max_length is not None: # Sum across different attention val...
Compute representation of the attention ready for the d3 visualization. Args: inp_text: list of strings, words to be displayed on the left of the vis out_text: list of strings, words to be displayed on the right of the vis enc_atts: numpy array, encoder self-attentions [num_layers, batch_size, nu...
def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts): """Compute representation of the attention ready for the d3 visualization. Args: inp_text: list of strings, words to be displayed on the left of the vis out_text: list of strings, words to be displayed on the right of the vis enc_...
Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string
def decode(tokens): """Decode a list of tokens to a unicode string. Args: tokens: a list of Unicode strings Returns: a unicode string """ token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens] ret = [] for i, token in enumerate(tokens): if i > 0 and token_is_alnum[i - 1] and token_...
Reads files matching a wildcard pattern, yielding the contents. Args: filepattern: A wildcard pattern matching one or more files. max_lines: If set, stop reading after reading this many lines. split_on_newlines: A boolean. If true, then split files by lines and strip leading and trailing whitespa...
def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True): """Reads files matching a wildcard pattern, yielding the contents. Args: filepattern: A wildcard pattern matching one or more files. max_lines: If set, stop reading after reading this many lines. split_on_newlines: A boolean. I...
Read the corpus and compute a dictionary of token counts. Args: text_filepattern: A pattern matching one or more files. corpus_max_lines: An integer; maximum total lines to read. split_on_newlines: A boolean. If true, then split files by lines and strip leading and trailing whitespace from each l...
def corpus_token_counts( text_filepattern, corpus_max_lines, split_on_newlines=True): """Read the corpus and compute a dictionary of token counts. Args: text_filepattern: A pattern matching one or more files. corpus_max_lines: An integer; maximum total lines to read. split_on_newlines: A boolean. I...
Read a vocab file and return a dictionary of token counts. Reads a two-column CSV file of tokens and their frequency in a dataset. The tokens are presumed to be generated by encode() or the equivalent. Args: text_filepattern: A pattern matching one or more files. max_lines: An integer; maximum total lin...
def vocab_token_counts(text_filepattern, max_lines): """Read a vocab file and return a dictionary of token counts. Reads a two-column CSV file of tokens and their frequency in a dataset. The tokens are presumed to be generated by encode() or the equivalent. Args: text_filepattern: A pattern matching one o...
Make a tf.train.Example for the problem. features[input_feature_name] = input_ids Also fills in any other required features with dummy values. Args: input_ids: list<int>. problem: Problem. input_feature_name: name of feature for input_ids. Returns: tf.train.Example
def _make_example(input_ids, problem, input_feature_name="inputs"): """Make a tf.train.Example for the problem. features[input_feature_name] = input_ids Also fills in any other required features with dummy values. Args: input_ids: list<int>. problem: Problem. input_feature_name: name of feature f...
Wraps function to make grpc requests with runtime args.
def make_grpc_request_fn(servable_name, server, timeout_secs): """Wraps function to make grpc requests with runtime args.""" stub = _create_stub(server) def _make_grpc_request(examples): """Builds and sends request to TensorFlow model server.""" request = predict_pb2.PredictRequest() request.model_sp...
Wraps function to make CloudML Engine requests with runtime args.
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...
Encodes inputs, makes request to deployed TF model, and decodes outputs.
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, ...
Basic 2-frame recurrent model with stochastic tower.
def next_frame_basic_recurrent(): """Basic 2-frame recurrent model with stochastic tower.""" hparams = basic_stochastic.next_frame_basic_stochastic_discrete() hparams.filter_double_steps = 2 hparams.hidden_size = 64 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.concat_inte...
Creates experiment function.
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 ...
Generate source and target data from a single file.
def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix, source_vocab_size, target_vocab_size): """Generate source and target data from a single file.""" filename = "parsing_{0}.pairs".format("train" if train else "dev") source_vocab = generator_utils.get_or_generate...
Generate source and target data from a single file.
def tabbed_parsing_character_generator(tmp_dir, train): """Generate source and target data from a single file.""" character_vocab = text_encoder.ByteTextEncoder() filename = "parsing_{0}.pairs".format("train" if train else "dev") pair_filepath = os.path.join(tmp_dir, filename) return text_problems.text2text_g...
Helper: make predictions and targets lists, check they match on length.
def _make_list(predictions, targets): """Helper: make predictions and targets lists, check they match on length.""" # Our models sometimes return predictions in lists, make it a list always. # TODO(lukaszkaiser): make abstractions for nested structures and refactor. if not isinstance(predictions, (list, tuple)...
Mean of the inputs but counting only those where targets != mask_id.
def masked_mean(inputs, targets, mask_id=None): """Mean of the inputs but counting only those where targets != mask_id.""" inputs = [x.astype(np.float32) for x in inputs] # We assume all elements in the list contribute equally. # TODO(lukaszkaiser): remove this assumption (e.g., when masks differ). length = l...
Calculate accuracy.
def accuracy(batch, model_predictions): """Calculate accuracy.""" _, targets = batch model_predictions, targets = _make_list(model_predictions, targets) correct = [] for (prediction, target) in zip(model_predictions, targets): predicted_class = np.argmax(prediction, axis=-1) correct.append(np.equal(pr...
Calculate negative 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])...
Calculate loss.
def loss(params, batch, model_predict, rng): """Calculate loss.""" inputs, targets = batch predictions = model_predict(inputs, params, rng=rng) predictions, targets = _make_list(predictions, targets) xent = [] for (pred, target) in zip(predictions, targets): xent.append(np.sum(pred * layers.one_hot(targ...
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 ...
Save State and optionally gin config.
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...
Evalaute on train and eval data, and log metrics.
def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng, train_sw=None, eval_sw=None, history=None): """Evalaute on train and eval data, and log metrics.""" step_log(step, "Evaluation") train_metrics, eval_metrics = [ evaluate( # pylint: disable=g-complex-comprehe...