text stringlengths 81 112k |
|---|
Read from the memory.
An external component can use the results via a simple MLP,
e.g., fn(x W_x + retrieved_mem W_m).
Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
access_logits: the logits for accessing the memory in shape of
[batch_size, length, memor... |
Write to the memory based on a combination of similarity and least used.
Based on arXiv:1607.00036v2 [cs.LG].
Args:
x: a tensor in the shape of [batch_size, length, depth].
access_logits: the logits for accessing the memory.
Returns:
the update op.
def write(self, x, access_logits):
... |
Reset the entries in the memory.
Args:
entries_to_reset: a 1D tensor.
Returns:
the reset op.
def reset(self, entries_to_reset):
"""Reset the entries in the memory.
Args:
entries_to_reset: a 1D tensor.
Returns:
the reset op.
"""
num_updates = tf.size(entries_to_rese... |
Called prior to self-attention, to incorporate memory items.
Args:
segment_number: an integer Tensor with shape [batch]
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: must be None. Attention normally allows this to be a
Tensor with shape [batch, lengt... |
Called after self-attention. The memory can be updated here.
Args:
token: Data returned by pre_attention, which can be used to carry over
state related to the current memory operation.
x: a Tensor of data after self-attention and feed-forward
Returns:
a (possibly modified) version of ... |
Define the training setup.
def _define_train(
train_env,
ppo_hparams,
eval_env_fn=None,
sampling_temp=1.0,
**collect_kwargs
):
"""Define the training setup."""
memory, collect_summary, train_initialization = (
_define_collect(
train_env,
ppo_hparams,
"ppo_tra... |
Train.
def _run_train(ppo_hparams,
event_dir,
model_dir,
restarter,
train_summary_op,
eval_summary_op,
initializers,
report_fn=None,
model_save_fn=None):
"""Train."""
summary_writer = tf.summary.... |
Metadata for rollouts.
def _rollout_metadata(batch_env):
"""Metadata for rollouts."""
batch_env_shape = batch_env.observ.get_shape().as_list()
batch_size = [batch_env_shape[0]]
shapes_types_names = [
# TODO(piotrmilos): possibly retrieve the observation type for batch_env
(batch_size + batch_env_sh... |
Collect trajectories.
Args:
batch_env: Batch environment.
ppo_hparams: PPO hparams, defined in tensor2tensor.models.research.rl.
scope: var scope.
frame_stack_size: Number of last observations to feed into the policy.
eval_phase: TODO(koz4k): Write docstring.
sampling_temp: Sampling temperatu... |
Deconvolution layer.
def deconv2d(
input_, output_shape, k_h, k_w, d_h, d_w, stddev=0.02, name="deconv2d"):
"""Deconvolution layer."""
with tf.variable_scope(name):
w = tf.get_variable(
"w", [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],
initializer=tf.random_normal_initializer(stdde... |
Basic parameters for a vanilla_gan.
def sliced_gan():
"""Basic parameters for a vanilla_gan."""
hparams = common_hparams.basic_params1()
hparams.optimizer = "adam"
hparams.learning_rate_constant = 0.0002
hparams.learning_rate_warmup_steps = 500
hparams.learning_rate_schedule = "constant * linear_warmup"
... |
Discriminator architecture based on InfoGAN.
Args:
x: input images, shape [bs, h, w, channels]
is_training: boolean, are we in train or eval model.
reuse: boolean, should params be re-used.
Returns:
out_logit: the output logits (before sigmoid).
def discriminator(self, x, is_training,... |
Generator outputting image in [0, 1].
def generator(self, z, is_training, out_shape):
"""Generator outputting image in [0, 1]."""
hparams = self.hparams
height, width, c_dim = out_shape
batch_size = hparams.batch_size
with tf.variable_scope(
"generator",
initializer=tf.random_normal... |
Body of the model.
Args:
features: a dictionary with the tensors.
Returns:
A pair (predictions, losses) where predictions is the generated image
and losses is a dictionary of losses (that get added for the final loss).
def body(self, features):
"""Body of the model.
Args:
fea... |
Make Inputs for built-in datasets.
Args:
num_devices: how many devices to build the inputs for.
dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix
with "t2t_".
data_dir: data directory.
input_name: optional, name of the inputs from the dictionary.
num_chunks: optio... |
Make random Inputs for debugging.
Args:
num_devices: how many devices to build the inputs for.
input_shape: the shape of inputs (including batch dimension).
input_dtype: the type of the inputs (int32 by default).
input_range: the range of inputs (defaults to (0, 255)).
output_shape: the shape of ... |
Takes a tf.Dataset and creates a numpy stream of ready batches.
def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False):
"""Takes a tf.Dataset and creates a numpy stream of ready batches."""
for example in tfds.as_numpy(dataset):
inp, out = example[0][input_name], example[1]
if len(o... |
Return train and evaluation datasets, feature info and supervised keys.
def _train_and_eval_dataset_v1(problem_name, data_dir):
"""Return train and evaluation datasets, feature info and supervised keys."""
assert not tf.executing_eagerly(), "tf.eager mode must be turned off."
problem = t2t_problems.problem(probl... |
Batching function.
def batch_fun(dataset, training, shapes, target_names, num_devices,
batch_size_per_device=32, batch_size=None, eval_batch_size=32,
bucket_length=32, buckets=None,
batch_shuffle_size=128, max_eval_length=None):
"""Batching function."""
del target_names
... |
Preprocessing for LM1B: filter out targets exceeding maximum length.
def lm1b_preprocess(dataset, training,
max_target_length=-1, max_eval_target_length=-1):
"""Preprocessing for LM1B: filter out targets exceeding maximum length."""
def target_right_length(_, target):
return tf.less(tf.sha... |
Shuffle and batch the given dataset.
def shuffle_and_batch_data(dataset,
target_names,
features_info,
training,
num_devices,
shuffle_buffer_size=1024,
prepro... |
Return train and eval batches with input name and shape.
def _train_and_eval_batches(dataset, data_dir, input_name, num_devices):
"""Return train and eval batches with input name and shape."""
(train_data, eval_data, features_info, keys) = train_and_eval_dataset(
dataset, data_dir)
input_names, target_name... |
Returns a Dataset that samples records from one or more Datasets.
Args:
datasets: A list of one or more Dataset objects to sample from.
pmf: A tensor of shape [len(datasets)], the probabilities to sample each
dataset with. This tensor is often constructed with the global_step. If
this is None, we... |
Computes the pmf of a schedule given the global_step.
Args:
schedule: A schedule tuple, see encode_schedule for details.
global_step: A scalar tensor, the step to query the schedule.
Returns:
A 1-D tensor of probs, the sampling distribution of the global_step.
def get_schedule_distribution(schedule, ... |
Returns the outputs of fns[i] with probability pmf[i].
Args:
pmf: A 1-D tensor of probabilities, the probability mass function.
fns: A list of callables that return tensors, same length as pmf.
rand: An optional scalar between 0.0 and 1.0, the output of an RNG.
Returns:
A tensor, the output of fns... |
Multi-dimensional linear interpolation.
Returns the multi-dimensional piecewise linear interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [*N], the x-coordinates of the interpolated values.
... |
Multi-dimensional step interpolation.
Returns the multi-dimensional step interpolant to a function with
given discrete data points (xp, fp), evaluated at x.
Note that *N and *M indicate zero or more dimensions.
Args:
x: An array of shape [*N], the x-coordinates of the interpolated values.
xp: An np.a... |
Create a probability-mass-function based on relative epoch rates.
if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems)
i.e. it takes each problem the same time to go through one epoch.
If epoch_rates is given, then these are the relative numbers of epochs
of each problem to go through in... |
Encodes a schedule tuple into a string.
Args:
schedule: A tuple containing (interpolation, steps, pmfs), where
interpolation is a string specifying the interpolation strategy, steps
is an int array_like of shape [N] specifying the global steps, and pmfs is
an array_like of shape [N, M] where pm... |
Decodes a string into a schedule tuple.
Args:
string: The string encoding of a schedule tuple.
Returns:
A schedule tuple, see encode_schedule for details.
def decode_schedule(string):
"""Decodes a string into a schedule tuple.
Args:
string: The string encoding of a schedule tuple.
Returns:
... |
Recursively converts iterables into tuples.
Args:
nested: A nested structure of items and iterables.
Returns:
A nested structure of items and tuples.
def tuplize(nested):
"""Recursively converts iterables into tuples.
Args:
nested: A nested structure of items and iterables.
Returns:
A nes... |
Returns a list of filepatterns, one for each problem.
def filepattern(self, *args, **kwargs):
"""Returns a list of filepatterns, one for each problem."""
return [p.filepattern(*args, **kwargs) for p in self.problems] |
Generates data for each problem.
def generate_data(self, *args, **kwargs):
"""Generates data for each problem."""
for p in self.problems:
p.generate_data(*args, **kwargs) |
Returns a dataset containing examples from multiple problems.
Args:
mode: A member of problem.DatasetSplit.
hparams: A tf.HParams object, the model hparams.
global_step: A scalar tensor used to compute the sampling distribution.
If global_step is None, we call tf.train.get_or_create_globa... |
Assumes that example contains both inputs and targets.
def normalize_example(self, example, hparams):
"""Assumes that example contains both inputs and targets."""
length = self.max_length(hparams)
def _to_constant_shape(tensor):
tensor = tensor[:length]
tensor = tf.pad(tensor, [(0, length - tf... |
Generates TF-Records for problems using a global vocabulary file.
def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1):
"""Generates TF-Records for problems using a global vocabulary file."""
global_vocab_filename = os.path.join(data_dir, self.vocab_filename)
if not tf.gfile.Exists(glob... |
Generates a non-padding mask for areas based on lengths.
Args:
feature_length: a tensor of [batch_size]
length: the length of the batch
max_area_size: the maximum area size considered
Returns:
mask: a tensor in shape of [batch_size, num_areas]
def lengths_to_area_mask(feature_length, length, max_a... |
Pools for an area in features_2d.
Args:
features_2d: a Tensor in a shape of [batch_size, height, width, depth].
area_width: the max width allowed for an area.
area_height: the max height allowed for an area.
batch_size: the batch size.
width: the width of the memory.
height: the height of the... |
Pools for each area based on a given pooling function (fn).
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
fn: the TF function for ... |
Computes area sums for features.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
name: the namescope.
Returns:
sum_image: A Te... |
Computes features for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
epsilon: the epsilon added to the variance for comp... |
Computes the key for each area.
Args:
features: a Tensor in a shape of [batch_size, height * width, depth].
max_area_width: the max width allowed for an area.
max_area_height: the max height allowed for an area.
height: the height of the image.
mode: whether to combine different area features or ... |
Dot-product area attention.
Args:
q: Tensor with shape [..., length_q, depth_k].
k: Tensor with shape [..., length_kv, depth_k]. Leading dimensions must
match with q.
v: Tensor with shape [..., length_kv, depth_v] Leading dimensions must
match with q.
bias: bias Tensor (see attention_bias... |
Setup directories.
def setup_directories(base_dir, subdirs):
"""Setup directories."""
base_dir = os.path.expanduser(base_dir)
tf.gfile.MakeDirs(base_dir)
all_dirs = {}
for subdir in subdirs:
if isinstance(subdir, six.string_types):
subdir_tuple = (subdir,)
else:
subdir_tuple = subdir
... |
Make a function that logs the duration since it was made.
def make_relative_timing_fn():
"""Make a function that logs the duration since it was made."""
start_time = time.time()
def format_relative_time():
time_delta = time.time() - start_time
return str(datetime.timedelta(seconds=time_delta))
def lo... |
Train supervised.
def train_supervised(problem, model_name, hparams, data_dir, output_dir,
train_steps, eval_steps, local_eval_frequency=None,
schedule="continuous_train_and_eval"):
"""Train supervised."""
if local_eval_frequency is None:
local_eval_frequency = FLAGS.l... |
Train the PPO agent in the simulated environment.
def train_agent(real_env, learner, world_model_dir, hparams, epoch):
"""Train the PPO agent in the simulated environment."""
initial_frame_chooser = rl_utils.make_initial_frame_chooser(
real_env, hparams.frame_stack_size, hparams.simulation_random_starts,
... |
Train the PPO agent in the real environment.
def train_agent_real_env(env, learner, hparams, epoch):
"""Train the PPO agent in the real environment."""
base_algo_str = hparams.base_algo
train_hparams = trainer_lib.create_hparams(hparams.base_algo_params)
rl_utils.update_hparams_from_hparams(
train_hpara... |
Train the world model on problem_name.
def train_world_model(
env, data_dir, output_dir, hparams, world_model_steps_num, epoch
):
"""Train the world model on problem_name."""
world_model_steps_num += world_model_step_increment(
hparams, is_initial_epoch=(epoch == 0)
)
model_hparams = trainer_lib.crea... |
Loads metrics for this epoch if they have already been written.
This reads the entire event file but it's small with just per-epoch metrics.
Args:
event_dir: TODO(koz4k): Document this.
epoch: TODO(koz4k): Document this.
Returns:
metrics.
def load_metrics(event_dir, epoch):
"""Loads metrics for ... |
Run the main training loop.
def training_loop(hparams, output_dir, report_fn=None, report_metric=None):
"""Run the main training loop."""
if report_fn:
assert report_metric is not None
# Directories
subdirectories = [
"data", "tmp", "world_model", ("world_model", "debug_videos"),
"policy", "ev... |
Single conv layer with relu, optional pooling, and dropout.
def conv_layer(x,
hidden_size,
kernel_size,
stride,
pooling_window,
dropout_rate,
dilation_rate,
name="conv"):
"""Single conv layer with relu, optional ... |
Hparams for GeneExpressionConv model.
def gene_expression_conv_base():
"""Hparams for GeneExpressionConv model."""
hparams = common_hparams.basic_params1()
batch_size = 10
output_length = 2048
inputs_per_output = 128
chunk_size = 4
input_length = output_length * inputs_per_output // chunk_size
hparams... |
Attend function.
def compress_self_attention_layer(x, hparams, name=None):
"""Attend function."""
with tf.variable_scope(name, default_name="compress_self_attention"):
x, xshape, _ = cia.maybe_reshape_4d_to_3d(x)
y = common_attention.multihead_attention(
common_layers.layer_preprocess(x, hparams),
... |
Computes negative ELBO, which is an upper bound on the negative likelihood.
Args:
data_dim: int-like indicating data dimensionality.
latent_dim: int-like indicating latent dimensionality.
average_reconstruction: Scalar Tensor indicating the reconstruction cost
averaged over all data dimensions and ... |
Multinomial sampling from a n-dimensional tensor.
Args:
x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial.
vocab_size: Number of classes in multinomial distribution.
sampling_method: String, "random" or otherwise deterministic.
temperature: Positive float.
Returns:
Tens... |
Latent prediction and loss.
Args:
latents_pred: Tensor of shape [..., depth].
latents_discrete_hot: Tensor of shape [..., vocab_size].
vocab_size: an int representing the vocab size.
hparams: HParams.
Returns:
sample: Tensor of shape [...], a sample from a multinomial distribution.
loss: T... |
Samples from the latent space in the autoencoder.
Args:
latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of
its first two dimensions are used. length_q is the latent length, which is
height * width * hparams.num_latents / (2**hparams.num_compress_steps).
inputs: Tensor of ... |
Residual block over inputs.
Runs a residual block consisting of
conv: kernel_size x kernel_size
conv: 1x1
dropout, add and normalize according to hparams.layer_postprocess_sequence.
Args:
inputs: Tensor of shape [batch, height, width, hparams.hidden_size].
hparams: HParams.
Returns:
Ten... |
Encoder that compresses 2-D inputs by 2**num_compress_steps.
Args:
inputs: Tensor of shape [batch, height, width, channels].
hparams: HParams.
strides: Tuple, strides for conv block.
kernel_size: Tuple, kernel window size for conv block.
name: string, variable scope.
Returns:
Tensor of sha... |
Encoder that compresses 2-D inputs by 2**num_compress_steps.
Args:
x: Tensor of shape [batch, height, width, channels].
hparams: HParams.
name: string, variable scope.
Returns:
Tensor of shape [batch, latent_length, hparams.hidden_size], where
latent_length is
hparams.num_latents * (he... |
Encoder that compresses 1-D inputs by 2**num_compress_steps.
Args:
x: Tensor of shape [batch, length, channels].
hparams: HParams.
name: string, variable scope.
Returns:
Tensor of shape [batch, latent_length, hparams.hidden_size], where
latent_length is
hparams.num_latents * length / 2... |
Decoder that decompresses 2-D inputs by 2**num_compress_steps.
Args:
inputs: Tensor of shape [batch, compress_height, compress_width, channels].
hparams: HParams.
strides: Tuple, strides for conv block.
kernel: Tuple, kernel window size for conv block.
name: string, variable scope.
Returns:
... |
Decoder that decompresses 2-D inputs by 2**num_compress_steps.
Args:
x: Tensor of shape [batch, compress_height, compress_width, channels].
hparams: HParams.
name: string, variable scope.
Returns:
Tensor of shape [batch, height, width, hparams.hidden_size].
def decompress_decoder_2d(x, hparams, n... |
Decoder that decompresses 1-D inputs by 2**num_compress_steps.
Args:
x: Tensor of shape [batch, compress_length, channels].
hparams: HParams.
name: string, variable scope.
Returns:
Tensor of shape [batch, length, hparams.hidden_size].
def decompress_decoder_1d(x, hparams, name=None):
"""Decoder... |
Transformer text encoder over inputs with unmasked full attention.
Args:
inputs: Tensor of shape [batch, length, 1, hparams.hidden_size].
target_space: int. Used for encoding inputs under a target space id.
hparams: HParams.
name: string, variable scope.
Returns:
encoder_output: Tensor of shap... |
Transformer image decoder over targets with local attention.
Args:
targets: Tensor of shape [batch, ...], and whose size is batch * height *
width * hparams.num_channels * hparams.hidden_size.
encoder_output: Tensor of shape [batch, length_kv, hparams.hidden_size].
ed_attention_bias: Tensor which b... |
Transformer decoder over latents using latent_attention_type.
Args:
x: Tensor of shape [batch, length_q, hparams.hidden_size]. length_q is the
latent length, which is
height * width * hparams.num_latents / (2**hparams.num_compress_steps).
encoder_output: Tensor of shape [batch, length_kv, hparams... |
Computes latents given inputs (typically, compressed targets).
def bottleneck_layer(inputs,
hparams,
name="discrete_bottleneck"):
"""Computes latents given inputs (typically, compressed targets)."""
[
latents_dense,
latents_discrete,
extra_loss,
emb... |
Transformer-based latent prediction model.
It is an autoregressive decoder over latents_discrete given inputs.
Args:
inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Inputs to
attend to for the decoder on latents.
ed_attention_bias: Tensor which broadcasts with shape [batch,
hp... |
Auto-encoder using a Transformer decoder and a prior over latent sequences.
Args:
inputs: Tensor of shape [batch, length, 1, hparams.hidden_size] or None.
targets: Tensor of shape [batch, ..., channels]. Ellipses may be 1 or 2
dimensions denoting sequence length.
target_space: int. Used for encodin... |
Performs a single IAF flow using scale and normalization transformations.
Args:
one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size,
latent_size, num_codes].
scale_weights: Tensor corresponding to lower triangular matrix used to
autoregressively generate scale matrix from ... |
Downloads all lsun files to directory unless they are there.
def _get_lsun(directory, category, split_name):
"""Downloads all lsun files to directory unless they are there."""
generator_utils.maybe_download(directory,
_LSUN_DATA_FILENAME % (category, split_name),
... |
Should be the same as in common_attention, avoiding import.
def _mixed_precision_is_enabled(hparams):
"""Should be the same as in common_attention, avoiding import."""
activation_dtype = hparams.activation_dtype
weight_dtype = hparams.weight_dtype
return activation_dtype == tf.float16 and weight_dtype == tf.fl... |
Minimize loss.
def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None):
"""Minimize loss."""
loss = weight_decay_and_noise(loss, hparams, learning_rate)
loss = tf.identity(loss, name="total_loss")
if variables is None:
variables = tf.trainable_variables()
# Print trainable variables.
... |
Apply weight decay and weight noise.
def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None):
"""Apply weight decay and weight noise."""
if var_list is None:
var_list = tf.trainable_variables()
decay_vars = [v for v in var_list]
noise_vars = [v for v in var_list if "/body/" in v.name]
w... |
Apply weight noise to vars in var_list.
def weight_noise(noise_rate, learning_rate, var_list):
"""Apply weight noise to vars in var_list."""
if not noise_rate:
return [tf.no_op()]
tf.logging.info("Applying weight noise scaled by learning rate, "
"noise_rate: %0.5f", noise_rate)
noise_op... |
Apply weight decay to vars in var_list.
def weight_decay(decay_rate, var_list, skip_biases=True):
"""Apply weight decay to vars in var_list."""
if not decay_rate:
return 0.
tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate)
weight_decays = []
for v in var_list:
# Weight decay.
... |
Log the sizes and shapes of variables, and the total size.
Args:
var_list: a list of variables; defaults to trainable_variables
tag: a string; defaults to "Trainable Variables"
verbose: bool, if True, log every weight; otherwise, log total size only.
def log_variable_sizes(var_list=None, tag=None, verbo... |
Summarize the variables.
Args:
var_list: a list of variables; defaults to trainable_variables.
tag: name scope of the summary; defaults to training_variables/.
def summarize_variables(var_list=None, tag=None):
"""Summarize the variables.
Args:
var_list: a list of variables; defaults to trainable_va... |
Get variable initializer from hparams.
def get_variable_initializer(hparams):
"""Get variable initializer from hparams."""
if not hparams.initializer:
return None
mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN,
value=hparams.initializer_gain,
... |
Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
def summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors.
Args:
tensor_dict: a dictionary of tensors.
tag: name scope of the summary; defaults to tensors/.
""... |
Extract image features from pretrained resnet model.
def image_embedding(images,
model_fn=resnet_v1_152,
trainable=True,
is_training=True,
weight_decay=0.0001,
batch_norm_decay=0.997,
batch_norm_epsi... |
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... |
Extract TIMIT datasets to directory unless directory/timit exists.
def _get_timit(directory):
"""Extract TIMIT datasets to directory unless directory/timit exists."""
if os.path.exists(os.path.join(directory, "timit")):
return
assert FLAGS.timit_paths
for path in FLAGS.timit_paths.split(","):
with tf.... |
Traverses directory collecting input and target files.
def _collect_data(directory, input_ext, target_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the data... |
Data generator for TIMIT transcription problem.
Args:
data_dir: path to the data directory.
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 inputs and labels to generate.
start_from: from which input to s... |
Reads a file to build a vocabulary.
Args:
filename: file to read list of words from.
vocab_dir: directory where to save the vocabulary.
vocab_name: vocab file name.
Returns:
text encoder.
def _build_vocab(filename, vocab_dir, vocab_name):
"""Reads a file to build a vocabulary.
Args:
file... |
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.
vo... |
Return a flat int32 tensor of shape [1, batch_size*length, 1].
def get_batch_coordinate(x):
"""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(
comm... |
Set of hyperparameters.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60
12.0 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00
Returns:
a hparams object
def aligned_base():
"""Set of hyperparameters.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min... |
version for languagemodel_wiki_scramble8k50.
languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92
3.3 steps/sec on P100
8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15
Returns:
a hparams object
def aligned_8k_grouped():
"""version for languagemodel_wiki_scramble8k50.
languagemodel_w... |
Reshapes first two dimensions in to single dimension.
Args:
tensor: Tensor to reshape of shape [A, B, ...]
Returns:
Reshaped tensor of shape [A*B, ...]
def _merge_beam_dim(tensor):
"""Reshapes first two dimensions in to single dimension.
Args:
tensor: Tensor to reshape of shape [A, B, ...]
Re... |
Reshapes first dimension back to [batch_size, beam_size].
Args:
tensor: Tensor to reshape of shape [batch_size*beam_size, ...]
batch_size: Tensor, original batch size.
beam_size: int, original beam size.
Returns:
Reshaped tensor of shape [batch_size, beam_size, ...]
def _unmerge_beam_dim(tensor, ... |
Tiles a given tensor by beam_size.
Args:
tensor: tensor to tile [batch_size, ...]
beam_size: How much to tile the tensor by.
Returns:
Tiled tensor [batch_size, beam_size, ...]
def _expand_to_beam_size(tensor, beam_size):
"""Tiles a given tensor by beam_size.
Args:
tensor: tensor to tile [bat... |
Returns the shape of the tensor but sets middle dims to None.
def get_state_shape_invariants(tensor):
"""Returns the shape of the tensor but sets middle dims to None."""
shape = tensor.shape.as_list()
for i in range(1, len(shape) - 1):
shape[i] = None
return tf.TensorShape(shape) |
Computes the i'th coordinate that contains the batch index for gathers.
Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which
batch the beam item is in. This will create the i of the i,j coordinate
needed for the gather.
Args:
batch_size: Batch size
beam_size: Size of the beam.
Returns... |
Fast gather implementation for models running on TPU.
This function use one_hot and batch matmul to do gather, which is faster
than gather_nd on TPU. For params that have dtype of int32 (sequences to
gather from), batch_gather is used to keep accuracy.
Args:
params: A tensor from which to gather values.
... |
Replaces the lower bits of each element with iota.
The iota is used to derive the index, and also serves the purpose to
make each element unique to break ties.
Args:
inputs: A tensor with rank of 2 and dtype of tf.float32.
[batch_size, original_size].
Returns:
A tensor after element wise transf... |
Creates the top k values in sorted order with indices.
Args:
inputs: A tensor with rank of 2. [batch_size, original_size].
k: An integer, number of top elements to select.
Returns:
topk_r2: A tensor, the k largest elements. [batch_size, k].
topk_indices_r2: A tensor, indices of the top k values. [... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.