INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Tiny setting with a tiny sv2p model.
def rlmb_tiny_sv2p(): """Tiny setting with a tiny sv2p model.""" hparams = rlmb_ppo_tiny() hparams.generative_model = "next_frame_sv2p" hparams.generative_model_params = "next_frame_sv2p_tiny" hparams.grayscale = False return hparams
Grid over games and frames, and 5 runs each for variance.
def rlmb_grid(rhp): """Grid over games and frames, and 5 runs each for variance.""" rhp.set_categorical("loop.game", ["breakout", "pong", "freeway"]) base = 100000 medium = base // 2 small = medium // 2 rhp.set_discrete("loop.num_real_env_frames", [base, medium, small]) # Dummy parameter to get 5 runs fo...
Merge multiple HParams into one with scopes.
def merge_unscoped_hparams(scopes_and_hparams): """Merge multiple HParams into one with scopes.""" merged_values = {} for (scope, hparams) in scopes_and_hparams: for key, value in six.iteritems(hparams.values()): scoped_key = "%s.%s" % (scope, key) merged_values[scoped_key] = value return hpara...
Split single HParams with scoped keys into multiple.
def split_scoped_hparams(scopes, merged_hparams): """Split single HParams with scoped keys into multiple.""" split_values = {scope: {} for scope in scopes} merged_values = merged_hparams.values() for scoped_key, value in six.iteritems(merged_values): scope = scoped_key.split(".")[0] key = scoped_key[len...
Create HParams suitable for training loop from scoped HParams. Args: scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These parameters are overrides for the base HParams created by create_loop_hparams. trial_id: str, trial identifier. This is used to register unique HParams ...
def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id): """Create HParams suitable for training loop from scoped HParams. Args: scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These parameters are overrides for the base HParams created by create_loop_hparam...
Get mapping from keyboard keys to actions. Required by gym.utils.play in environment or top level wrapper. Returns: { Unicode code point for keyboard key: action (formatted for step()), ... }
def get_keys_to_action(self): """Get mapping from keyboard keys to actions. Required by gym.utils.play in environment or top level wrapper. Returns: { Unicode code point for keyboard key: action (formatted for step()), ... } """ # Based on gym AtariEnv.get_keys_to_actio...
Pass action to underlying environment(s) or perform special action.
def step(self, action): """Pass action to underlying environment(s) or perform special action.""" # Special codes if action in self._player_actions(): envs_step_tuples = self._player_actions()[action]() elif self._wait and action == self.name_to_action_num["NOOP"]: # Ignore no-op, do not pas...
Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Expanded observation array.
def _augment_observation(self, ob, reward, cumulative_reward): """"Expand observation array with additional information header (top rows). Args: ob: observation reward: reward to be included in header. cumulative_reward: total cumulated reward to be included in header. Returns: Exp...
Construct observation, return usual step tuple. Args: envs_step_tuples: tuples. Returns: Step tuple: ob, reward, done, info ob: concatenated images [simulated observation, real observation, difference], with additional informations in header. reward: real environment rewa...
def _player_step_tuple(self, envs_step_tuples): """Construct observation, return usual step tuple. Args: envs_step_tuples: tuples. Returns: Step tuple: ob, reward, done, info ob: concatenated images [simulated observation, real observation, difference], with additional inform...
Reset simulated and real environments.
def reset(self): """Reset simulated and real environments.""" self._frame_counter = 0 ob_real = self.real_env.reset() # Initialize simulated environment with frames from real one. self.sim_env.add_to_initial_stack(ob_real) for _ in range(3): ob_real, _, _, _ = self.real_env.step(self.name_...
Perform step(action) on environments and update initial_frame_stack.
def _step_envs(self, action): """Perform step(action) on environments and update initial_frame_stack.""" self._frame_counter += 1 real_env_step_tuple = self.real_env.step(action) sim_env_step_tuple = self.sim_env.step(action) self.sim_env.add_to_initial_stack(real_env_step_tuple[0]) return self....
Augment observation, return usual step tuple.
def _player_step_tuple(self, envs_step_tuples): """Augment observation, return usual step tuple.""" ob, reward, done, info = envs_step_tuples["env"] ob = self._augment_observation(ob, reward, self.cumulative_reward) return ob, reward, done, info
Compute time first and second-order derivative channels. Args: filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1] name: scope name Returns: float32 tensor with shape [batch_size, len, num_bins, 3]
def add_delta_deltas(filterbanks, name=None): """Compute time first and second-order derivative channels. Args: filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1] name: scope name Returns: float32 tensor with shape [batch_size, len, num_bins, 3] """ delta_filter = np.array([2,...
Implement mel-filterbank extraction using tf ops. Args: waveforms: float32 tensor with shape [batch_size, max_len] sample_rate: sampling rate of the waveform dither: stddev of Gaussian noise added to waveform to prevent quantization artefacts preemphasis: waveform high-pass filtering constant ...
def compute_mel_filterbank_features( waveforms, sample_rate=16000, dither=1.0 / np.iinfo(np.int16).max, preemphasis=0.97, frame_length=25, frame_step=10, fft_length=None, window_fn=functools.partial(tf.contrib.signal.hann_window, periodic=True), lower_edge_hertz=80.0, upper_edge_hertz=7600.0, num_me...
Plays the env problem by randomly sampling actions for `num_steps`.
def play_env_problem_randomly(env_problem, num_steps): """Plays the env problem by randomly sampling actions for `num_steps`.""" # Reset all environments. env_problem.reset() # Play all environments, sampling random actions each time. for _ in range(num_steps): # Sample batc...
Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: train_indices (np.array of Integers): random integers for training. shape = [num_samples, length] test_indi...
def generate_plaintext_random(plain_vocab, distribution, train_samples, length): """Generates samples of text from the provided vocabulary. Args: plain_vocab: vocabulary. distribution: distribution. train_samples: samples for training. length: length. Returns: t...
Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is positive. Returns: ciphertext (list of Strings): ...
def encipher_shift(plaintext, plain_vocab, shift): """Encrypt plain text with a single shift layer. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. shift (Integer): number of shift, shift to the right if shift is...
Encrypt plain text with given key. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. key (list of Integer): key to encrypt cipher using Vigenere table. Returns: ciphertext (list of Strings): encrypted plain te...
def encipher_vigenere(plaintext, plain_vocab, key): """Encrypt plain text with given key. Args: plaintext (list of list of Strings): a list of plain text to encrypt. plain_vocab (list of Integer): unique vocabularies being used. key (list of Integer): key to encrypt cipher using Vigenere table. Retu...
A stack of super_lm layers. Args: inputs: a list of Tensors attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) hparams: hyperparameters for model mp: a Parallelism object padding: a string Returns: y: a list of Tensors extra_loss: an op...
def _super_stack(inputs, attention_bias, hparams, mp, padding="LEFT"): """A stack of super_lm layers. Args: inputs: a list of Tensors attention_bias: list of bias Tensor for self-attention (see common_attention.attention_bias()) ...
Set of hyperparameters.
def super_lm_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.hidden_size = 512 hparams.moe_hidden_sizes = "512" hparams.batch_size = 16384 hparams.max_length = 0 # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. h...
Add mixture of experts with ~1B params.
def super_lm_moe(): """Add mixture of experts with ~1B params.""" hparams = super_lm_base() hparams.layers = ( ("n,att,m,d,a," "n,moe,m,d,a,") * 4 + "n,ffn,d") hparams.moe_num_experts = 32 hparams.moe_hidden_sizes = "1024" return hparams
Series of architectural experiments on Translation. # run on 8-core setup 119M params, einsum=0.95e13 Returns: a hparams
def xmoe_tr_dense_2k(): """Series of architectural experiments on Translation. # run on 8-core setup 119M params, einsum=0.95e13 Returns: a hparams """ hparams = mtf_transformer2.mtf_bitransformer_base() hparams.encoder_layers = ["self_att", "drd"] * 4 hparams.decoder_layers = ["self_att", "enc_a...
Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams
def xmoe_tr_1d(): """Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams """ hparams = xmoe_tr_dense_2k() hparams.encoder_layers = ["self_att", "moe_1d"] * 4 hparams.decoder_layers = ["self_att", "enc_att", "moe_1d"] * 4 hparams.layout = "batch:batch;experts:batch" h...
Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams
def xmoe_tr_2d(): """Mixture of experts (16 experts). 623M Params, einsum=1.09e13 Returns: a hparams """ hparams = xmoe_tr_dense_2k() hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.encoder_layers = ["...
Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util log-ppl xmoe_dense_4k ...
def xmoe_dense_4k(): """Series of architectural experiments on cheap language models. For all of these architectures, we run on languagemodel_lm1b8k_packed for 32000 steps. All log-perplexities are per-token - multiply by 1.298 for per-word Results: model params(M) einsum alltoall mxu-util...
Mixture of experts (16 experts).
def xmoe_top_2(): """Mixture of experts (16 experts).""" hparams = xmoe_dense_4k() moe.set_default_moe_hparams(hparams) hparams.mesh_shape = "all:8" hparams.layout = "batch:all;experts:all" return hparams
Two-dimensional hierarchical mixture of 16 experts.
def xmoe_2d(): """Two-dimensional hierarchical mixture of 16 experts.""" hparams = xmoe_top_2() hparams.decoder_layers = ["att", "hmoe"] * 4 hparams.mesh_shape = "b0:2;b1:4" hparams.outer_batch_size = 4 hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0" hparams.moe_num_experts = [4, ...
Series of architectural experiments on language modeling. Larger models than the ones above. All models are trained on sequences of 1024 tokens. We assume infinite training data, so no dropout necessary. We process 2^36 tokens in training = 524288 steps at batch size 128 TODO(noam): find a large enough da...
def xmoe2_dense(sz): """Series of architectural experiments on language modeling. Larger models than the ones above. All models are trained on sequences of 1024 tokens. We assume infinite training data, so no dropout necessary. We process 2^36 tokens in training = 524288 steps at batch size 128 TODO(noa...
Model incorporating mixture-of-experts and local-attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams
def xmoe2_v1(): """Model incorporating mixture-of-experts and local-attention. ~6B parameters 32 experts in 3 hierarchichal moe layers. Returns: a hparams """ hparams = xmoe2_dense(0) moe.set_default_moe_hparams(hparams) hparams.decoder_layers = ( ["local_att", "local_att", "drd", "a...
128 experts, ~25B params - Train for 131072 steps on 8x8.
def xmoe2_v1_x128(): """128 experts, ~25B params - Train for 131072 steps on 8x8.""" hparams = xmoe2_v1() hparams.moe_num_experts = [16, 8] hparams.outer_batch_size = 8 hparams.mesh_shape = "b0:8;b1:16" hparams.batch_size = 512 hparams.learning_rate_decay_steps = 16384 return hparams
Test on local cpu.
def xmoe2_tiny(): """Test on local cpu.""" hparams = xmoe2_v1() hparams.decoder_layers = [ "local_att", "att", "compressed_att", "drd", "hmoe"] hparams.d_model = 128 hparams.moe_hidden_size = 512 hparams.outer_batch_size = 0 hparams.batch_size = 2 hparams.mesh_shape = "" hparams.activation_dtype...
With sequence length 4096.
def xmoe2_v1_l4k(): """With sequence length 4096.""" hparams = xmoe2_v1() hparams.batch_size = 32 hparams.max_length = 4096 hparams.split_to_length = 4096 hparams.reshape_logits_hack = True return hparams
With sequence length 4096.
def xmoe2_v1_l4k_local_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "local_att" if l == "att" else l for l in hparams.decoder_layers] return hparams
With compressed attention.
def xmoe2_v1_l4k_compressed_c4(): """With compressed attention.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "compressed_att" if l == "att" else l for l in hparams.decoder_layers] hparams.compression_factor = 4 return hparams
With sequence length 4096.
def xmoe2_v1_l4k_global_only(): """With sequence length 4096.""" hparams = xmoe2_v1_l4k() hparams.decoder_layers = [ "att" if l == "local_att" else l for l in hparams.decoder_layers] return hparams
Set of architectural experiments - language model on wikipedia on a 2x2. 1 epoch = ~180k steps at batch size 32 - we may never finish an epoch! Returns: a hparams
def wiki_2x2_base(): """Set of architectural experiments - language model on wikipedia on a 2x2. 1 epoch = ~180k steps at batch size 32 - we may never finish an epoch! Returns: a hparams """ hparams = mtf_transformer.mtf_transformer_base_lm() hparams.shared_embedding_and_softmax_weights = False # no...
Replace tokens instead of masking.
def denoise_z15(): """Replace tokens instead of masking.""" hparams = xmoe2_dense_0() hparams.decoder_type = "denoising" hparams.noising_spec_train = {"type": "random_zipfian", "prob": 0.15} hparams.noising_use_eval_during_train = 0.25 return hparams
Denoising experiment.
def denoise_v1_m15(): """Denoising experiment.""" hparams = xmoe2_v1() # no local attention # TODO(noam): non-masked version of local-attention hparams.decoder_layers = [ "att" if l == "local_att" else l for l in hparams.decoder_layers] hparams.decoder_type = "denoising" hparams.noising_spec_train =...
Downloads and extracts the dataset. Args: tmp_dir: temp directory to download and extract the dataset data_dir: The base directory where data and vocab files are stored. Returns: tmp_dir: temp directory containing the raw data.
def _download_mlu_data(tmp_dir, data_dir): """Downloads and extracts the dataset. Args: tmp_dir: temp directory to download and extract the dataset data_dir: The base directory where data and vocab files are stored. Returns: tmp_dir: temp directory containing the raw data. """ if not tf.gfile.Ex...
Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram size Returns: collections.Counter with ID tuples as keys and 1s as values.
def _get_ngram_counter(ids, n): """Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram size Returns: collections.Counter with ID tuples as keys and 1s as values. """ # Remove zero IDs used to pad the sequence. ids = [to...
Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Returns: Fbeta score.
def _get_fbeta_score(true_positives, selected, relevant, beta=1): """Compute Fbeta score. Args: true_positives: Number of true positive ngrams. selected: Number of selected ngrams. relevant: Number of relevant ngrams. beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only. Ret...
Compute the addition score (Equation 4 in the paper).
def get_addition_score(source_counts, prediction_counts, target_counts): """Compute the addition score (Equation 4 in the paper).""" added_to_prediction_counts = prediction_counts - source_counts true_positives = sum((added_to_prediction_counts & target_counts).values()) selected = sum(added_to_prediction_count...
Compute the keep score (Equation 5 in the paper).
def get_keep_score(source_counts, prediction_counts, target_counts): """Compute the keep score (Equation 5 in the paper).""" source_and_prediction_counts = source_counts & prediction_counts source_and_target_counts = source_counts & target_counts true_positives = sum((source_and_prediction_counts & ...
Compute the deletion score (Equation 6 in the paper).
def get_deletion_score(source_counts, prediction_counts, target_counts, beta=0): """Compute the deletion score (Equation 6 in the paper).""" source_not_prediction_counts = source_counts - prediction_counts source_not_target_counts = source_counts - target_counts true_positives = sum((source_not_prediction_count...
Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece IDs list_of_targets: a list of target ID lists / np.arrays max_gram_size: int. largest n-gram size we care about (e.g. 3 ...
def get_sari_score(source_ids, prediction_ids, list_of_targets, max_gram_size=4, beta_for_deletion=0): """Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece ID...
Computes the SARI scores from the given source, prediction and targets. Args: source_ids: A 2D tf.Tensor of size (batch_size , sequence_length) prediction_ids: A 2D tf.Tensor of size (batch_size, sequence_length) target_ids: A 3D tf.Tensor of size (batch_size, number_of_targets, sequence_length) ...
def get_sari(source_ids, prediction_ids, target_ids, max_gram_size=4): """Computes the SARI scores from the given source, prediction and targets. Args: source_ids: A 2D tf.Tensor of size (batch_size , sequence_length) prediction_ids: A 2D tf.Tensor of size (batch_size, sequence_length) target_ids: A 3D...
Computes the SARI scores from the given source, prediction and targets. An approximate SARI scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4. Also, this does not have beam search. Args: predictions: tensor, model predictions. ...
def sari_score(predictions, labels, features, **unused_kwargs): """Computes the SARI scores from the given source, prediction and targets. An approximate SARI scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4. Also, this does not have...
Download all MNIST files to directory unless they are there.
def _get_mnist(directory): """Download all MNIST files to directory unless they are there.""" for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME, _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME ]: generator_utils.maybe_download(directory, filename, _MNIST_URL + filen...
Extract images from an MNIST file into a numpy array. Args: filename: The path to an MNIST images file. num_images: The number of images in the file. Returns: A numpy array of shape [number_of_images, height, width, channels].
def _extract_mnist_images(filename, num_images): """Extract images from an MNIST file into a numpy array. Args: filename: The path to an MNIST images file. num_images: The number of images in the file. Returns: A numpy array of shape [number_of_images, height, width, channels]. """ with gzip.ope...
Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels]
def _extract_mnist_labels(filename, num_labels): """Extract labels from an MNIST file into integers. Args: filename: The path to an MNIST labels file. num_labels: The number of labels in the file. Returns: A int64 numpy array of shape [num_labels] """ with gzip.open(filename) as bytestream: ...
Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. data_filename: file that contains features data. label_filename: file that contains labels. ...
def mnist_common_generator(tmp_dir, training, how_many, data_filename, label_filename, start_from=0): """Image generator for MNIST. Args: tmp_dir: path to temporary storage dir...
Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which image to start. Returns: An instance of image_generator that produ...
def mnist_generator(tmp_dir, training, how_many, start_from=0): """Image generator for MNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which imag...
Download all FashionMNIST files to directory unless they are there.
def _get_fashion_mnist(directory): """Download all FashionMNIST files to directory unless they are there.""" # Fashion mnist files have the same names as MNIST. # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir. for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_...
Image generator for FashionMNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which image to start. Returns: An instance of image_generator tha...
def fashion_mnist_generator(tmp_dir, training, how_many, start_from=0): """Image generator for FashionMNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: ...
Generates synthetic timeseries using input parameters. Each generated timeseries has timeseries_length data points. Parameters for each timeseries are specified by timeseries_params. Args: timeseries_length: Number of data points to generate for each timeseries. timeseries_params: Parameters used to gen...
def generate_data(timeseries_length, timeseries_params): """Generates synthetic timeseries using input parameters. Each generated timeseries has timeseries_length data points. Parameters for each timeseries are specified by timeseries_params. Args: timeseries_length: Number of data points to generate for ...
Basic 2-frame conv model with stochastic tower.
def next_frame_basic_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iteration...
Basic 2-frame conv model with stochastic tower.
def next_frame_sampling_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iterations_1st_st...
Basic 2-frame conv model with stochastic discrete latent.
def next_frame_basic_stochastic_discrete(): """Basic 2-frame conv model with stochastic discrete latent.""" hparams = basic_deterministic_params.next_frame_sampling() hparams.batch_size = 4 hparams.video_num_target_frames = 6 hparams.scheduled_sampling_mode = "prob_inverse_lin" hparams.scheduled_sampling_de...
Map the function f to the nested structure x (dicts, tuples, lists).
def nested_map(x, f): """Map the function f to the nested structure x (dicts, tuples, lists).""" if isinstance(x, list): return [nested_map(y, f) for y in x] if isinstance(x, tuple): return tuple([nested_map(y, f) for y in x]) if isinstance(x, dict): return {k: nested_map(x[k], f) for k in x} retu...
Get a structure of shapes for a structure of nested arrays.
def shapes(x): """Get a structure of shapes for a structure of nested arrays.""" def shape(x): try: return x.shape except Exception: # pylint: disable=broad-except return [] return nested_map(x, shape)
Get a structure of sizes for a structure of nested arrays.
def sizes(x): """Get a structure of sizes for a structure of nested arrays.""" def size(x): try: return x.size except Exception: # pylint: disable=broad-except return 0 return nested_map(x, size)
Find the frame with the caller on the stack.
def _find_frame(stack, start=0): """Find the frame with the caller on the stack.""" # We want to find the first place where the layer was called # that is *not* an __init__ function of an inheriting layer. frame = inspect.getframeinfo(stack[start][0]) # If we are in an init, move on. if frame.function == '_...
Shorten file path in error lines for more readable tracebacks.
def _shorten_file_path(line): """Shorten file path in error lines for more readable tracebacks.""" start = line.lower().find('file') if start < 0: return line first_quote = line.find('"', start) if first_quote < 0: return line second_quote = line.find('"', first_quote + 1) if second_quote < 0: ...
Cleaned-up form of traceback.
def _short_traceback(skip=3): """Cleaned-up form of traceback.""" counter, res = 0, [] # Skipping 3 lines by default: the top (useless) and self-call. lines = traceback.format_exc().splitlines()[skip:] for l in lines: res.append(_shorten_file_path(l)) if counter % 2 == 1: res.append('') coun...
Create a layer class from a function.
def layer(output_shape=None, new_parameters=None): """Create a layer class from a function.""" def layer_decorator(call): """Decorating the call function.""" def output_shape_fun(self, input_shape): if output_shape is None: return input_shape kwargs = self._init_kwargs # pylint: disable...
Initialize the layer given an input shape and rng. Returns new_parameters(input_shape, rng) on the first call and () on any subsequent call, as the layer is already initialized. This is used for networks that share parameters, so the layer only produces them once. Note that all arguments and return va...
def initialize(self, input_shape, rng): """Initialize the layer given an input shape and rng. Returns new_parameters(input_shape, rng) on the first call and () on any subsequent call, as the layer is already initialized. This is used for networks that share parameters, so the layer only produces them o...
Returns dict<str ref_url, str ref_content>.
def _references_content(ref_files): """Returns dict<str ref_url, str ref_content>.""" example_spec = { "url": tf.FixedLenFeature([], tf.string), "content": tf.FixedLenFeature([], tf.string), } data = {} for ex in generator_utils.tfrecord_iterator( ref_files, gzipped=True, example_spec=exampl...
Urls for chunk: dict<str wiki_url, list<str> ref_urls>.
def _wiki_urls_for_shard(shard_id, urls_dir=None): """Urls for chunk: dict<str wiki_url, list<str> ref_urls>.""" urls_dir = urls_dir or WIKI_URLS_DIR urls_filepath = os.path.join(urls_dir, WIKI_URLS_FILE % shard_id) with tf.gfile.GFile(urls_filepath) as f: return json.loads(f.read())
Generates WikipediaArticles from GCS that are part of shard shard_id.
def _wiki_articles(shard_id, wikis_dir=None): """Generates WikipediaArticles from GCS that are part of shard shard_id.""" if not wikis_dir: wikis_dir = WIKI_CONTENT_DIR with tf.Graph().as_default(): dataset = tf.data.TFRecordDataset( cc_utils.readahead( os.path.join(wikis_dir, WIKI_CON...
Rank and return reference paragraphs by tf-idf score on title tokens.
def rank_reference_paragraphs(wiki_title, references_content, normalize=True): """Rank and return reference paragraphs by tf-idf score on title tokens.""" normalized_title = _normalize_text(wiki_title) title_tokens = _tokens_to_score( set(tokenizer.encode(text_encoder.native_to_unicode(normalized_title)))) ...
Produce examples from shard_ids to out_filepaths.
def produce_examples(shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path, out_filepaths): """Produce examples from shard_ids to out_filepaths.""" # * Join the Wikipedia articles with their references # * Run Tf-idf to sort reference paragraphs # * Encode the Wikipedia and reference text wi...
Encodes sections with vocab. Returns ids and section boundaries.
def _encode_wiki_sections(sections, vocab): """Encodes sections with vocab. Returns ids and section boundaries.""" ids = [] section_boundaries = [] for i, section in enumerate(sections): if i > 0: # Skip including article title ids.extend(vocab.encode(_format_title(_normalize_text(section.title)...
Extract references from WET files into sharded output files.
def extract_references_from_wets(wet_files, metadata_dir, out_dir, tmp_dir=None): """Extract references from WET files into sharded output files.""" # Setup output files shard_files = make_ref_shard_files(out_dir) num_refs = 0 for i, wet_file in enumerate(wet_files): num_...
Extract pages from an xml dump. Args: dump: a unicode string Returns: a list of unicode strings
def _dump_to_pages(dump): """Extract pages from an xml dump. Args: dump: a unicode string Returns: a list of unicode strings """ pos = 0 ret = [] start_tag = u"<page>\n" end_tag = u"</page>\n" while True: start_pos = dump.find(start_tag, pos) if start_pos == -1: break start_...
Extract the title from a page. Args: page: a unicode string Returns: a unicode string
def _page_to_title(page): """Extract the title from a page. Args: page: a unicode string Returns: a unicode string """ # print("page=%s" % page) start_tag = u"<title>" end_tag = u"</title>" start_pos = page.find(start_tag) end_pos = page.find(end_tag) assert start_pos != -1 assert end_pos...
Extract the text from a page. Args: page: a unicode string Returns: a unicode string
def _page_to_text(page): """Extract the text from a page. Args: page: a unicode string Returns: a unicode string """ # text start tag looks like "<text ..otherstuff>" start_pos = page.find(u"<text") assert start_pos != -1 end_tag_pos = page.find(u">", start_pos) assert end_tag_pos != -1 end...
Remove everything found between instances of start_string and end_string. Replace each such instance with replace_fn(removed_text) e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x) = u"the fat cat sat" Args: text: a unicode string start_string: a unicode string end_s...
def _find_and_replace(text, start_string, end_string, replace_fn): """Remove everything found between instances of start_string and end_string. Replace each such instance with replace_fn(removed_text) e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x) = u"the fat cat sat" Args:...
Remove double brackets (internal links) but leave the viewable text. Args: text: a unicode string Returns: a unicode string
def _remove_double_brackets(text): """Remove double brackets (internal links) but leave the viewable text. Args: text: a unicode string Returns: a unicode string """ def replacement_fn(s): if u":" in s: # this is probably a category or something like that. return "" # keep the par...
A stack of self attention layers.
def image_encoder(image_feat, hparams, name="image_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = image_feat image_hidden_size = hparams.image_hidden_size or hparams.hidden_size image_...
Prepare question encoder. Args: inputs: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor, bottom of encoder stack encoder_self_attention_bias: a bias tensor for use in encoder self-attention
def prepare_question_encoder(inputs, hparams): """Prepare question encoder. Args: inputs: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor, bottom of encoder stack encoder_self_attention_bias: a bias tensor for use in encoder self-attention """ encoder_input = inputs ...
A stack of self attention layers.
def question_encoder(question, question_self_attention_bias, hparams, name="question_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = question with tf.varia...
Attention on image feature with question as query.
def attn(image_feat, query, hparams, name="attn", save_weights_to=None, make_image_summary=True): """Attention on image feature with question as query.""" with tf.variable_scope(name, "attn", values=[image_feat, query]): total_key_depth = hparams.attention_key_channe...
Multi layer perceptron with dropout and relu activation.
def mlp(feature, hparams, name="mlp"): """Multi layer perceptron with dropout and relu activation.""" with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_size = hparams.mlp_size for _ in range(num_mlp_layers): feature = common_layers.dense(feature, ml...
Prepare encoder. Args: image_feat: a Tensor. question: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor, bottom of encoder stack encoder_self_attention_bias: a bias tensor for use in encoder self-attention
def prepare_image_question_encoder(image_feat, question, hparams): """Prepare encoder. Args: image_feat: a Tensor. question: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor, bottom of encoder stack encoder_self_attention_bias: a bias tensor for use in encoder self-att...
A stack of self attention layers.
def image_question_encoder(encoder_inputs, encoder_self_attention_bias, hparams, query=None, name="image_question_encoder", save_weights_to=None, make_image_s...
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 decoder(decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, name="decoder", save_weights_to=None, make_image_summary=True,): """A stack of transformer layers. Args: decoder_i...
Iterative encoder decoder.
def iterative_encoder_decoder(encoder_input, encoder_self_attention_bias, encoder_decoder_attention_bias, query, hparams): """Iterative encoder decoder.""" for _ in range(hparams.num_rec_steps): ...
VQA attention baseline hparams.
def vqa_self_attention_base(): """VQA attention baseline hparams.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = True, hparams.optimizer = "adam" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.997 hparams.optimizer_adam_epsilon = ...
Big model.
def vqa_self_attention_feature_batch1024_big(): """Big model.""" hparams = vqa_self_attention_feature_batch1024() hparams.learning_rate_constant = 7e-4 hparams.batch_size = 256 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.num_heads = 16 hparams.layer_prepostprocess_dropout = 0.3 hpara...
A default set of length-bucket boundaries.
def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1): """A default set of length-bucket boundaries.""" assert length_bucket_step > 1.0 x = min_length boundaries = [] while x < max_length: boundaries.append(x) x = max(x + 1, int(x * length_bucket_step)) return boundaries
A batching scheme based on model hyperparameters. Every batch contains a number of sequences divisible by `shard_multiplier`. Args: batch_size: int, total number of tokens in a batch. max_length: int, sequences longer than this will be skipped. Defaults to batch_size. min_length_bucket: int ...
def batching_scheme(batch_size, max_length, min_length_bucket, length_bucket_step, drop_long_sequences=False, shard_multiplier=1, length_multiplier=1, min_length=0): """A batchin...
Wrapper around _batching_scheme with hparams.
def hparams_to_batching_scheme(hparams, drop_long_sequences=False, shard_multiplier=1, length_multiplier=1): """Wrapper around _batching_scheme with hparams.""" return batching_scheme( batch_size=hparams.batch_size, ...
Pads unknown features' dimensions for TPU.
def pad_for_tpu(shapes_dict, hparams, max_length): """Pads unknown features' dimensions for TPU.""" padded_shapes = {} def get_filler(specified_max_length): if not specified_max_length: return max_length return min(specified_max_length, max_length) inputs_none_filler = get_filler(hparams.max_inp...
Set the right shapes for the features.
def standardize_shapes(features, batch_size=None): """Set the right shapes for the features.""" for fname in ["inputs", "targets"]: if fname not in features: continue f = features[fname] while len(f.get_shape()) < 4: f = tf.expand_dims(f, axis=-1) features[fname] = f if batch_size: ...
Return the number of TFRecords in a file.
def _file_num_records_cached(filename): """Return the number of TFRecords in a file.""" # Cache the result, as this is expensive to compute if filename in _file_num_records_cache: return _file_num_records_cache[filename] ret = 0 for _ in tf.python_io.tf_record_iterator(filename): ret += 1 _file_num_...
Pad batch dim of features to nearest multiple of batch_multiple.
def pad_batch(features, batch_multiple): """Pad batch dim of features to nearest multiple of batch_multiple.""" feature = list(features.items())[0][1] batch_size = tf.shape(feature)[0] mod = batch_size % batch_multiple has_mod = tf.cast(tf.cast(mod, tf.bool), tf.int32) batch_padding = batch_multiple * has_m...
Builds input pipeline for problem. Args: dataset: the dataset to make input function from. filepattern: the pattern of files to read from. skip_random_fraction_when_training: whether to skip randomly when training. batch_size_means_tokens_param: whether batch size should mean tokens. batch_size_m...
def input_fn(dataset, filepattern, skip_random_fraction_when_training, batch_size_means_tokens_param, batch_size_multiplier, max_length, mode, hparams, data_dir=None, params=None, config=Non...
Generate example dicts.
def dataset_generator(filepath, dataset, chunk_size=1, start_idx=None, end_idx=None): """Generate example dicts.""" encoder = dna_encoder.DNAEncoder(chunk_size=chunk_size) with h5py.File(filepath, "r") as h5_file: # Get in...
Generate start and end indices per outfile.
def generate_shard_args(outfiles, num_examples): """Generate start and end indices per outfile.""" num_shards = len(outfiles) num_examples_per_shard = num_examples // num_shards start_idxs = [i * num_examples_per_shard for i in range(num_shards)] end_idxs = list(start_idxs) end_idxs.pop(0) end_idxs.append...
Convert single h5 record to an example dict.
def to_example_dict(encoder, inputs, mask, outputs): """Convert single h5 record to an example dict.""" # Inputs bases = [] input_ids = [] last_idx = -1 for row in np.argwhere(inputs): idx, base_id = row idx, base_id = int(idx), int(base_id) assert idx > last_idx # if not, means 2 True values i...