Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def dataset_to_stream(dataset, input_name, num_chunks=0, append_targets=False):
for example in tfds.as_numpy(dataset):
inp, out = example[0][input_name], example[1]
if len(out.shape) > 1 and out.shape[-1] == 1:
out = np.squeeze(out, axis=-1)
if num_chu... | [
"Takes a tf.Dataset and creates a numpy stream of ready batches."
] |
Please provide a description of the function:def _train_and_eval_dataset_v1(problem_name, data_dir):
assert not tf.executing_eagerly(), "tf.eager mode must be turned off."
problem = t2t_problems.problem(problem_name)
train_dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, data_dir)
train_dataset = train... | [
"Return train and evaluation datasets, feature info and supervised keys."
] |
Please provide a description of the 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):
del target_names
... | [
"Batching function."
] |
Please provide a description of the function:def lm1b_preprocess(dataset, training,
max_target_length=-1, max_eval_target_length=-1):
def target_right_length(_, target):
return tf.less(tf.shape(target)[0], max_target_length + 1)
def eval_target_right_length(_, target):
return tf.les... | [
"Preprocessing for LM1B: filter out targets exceeding maximum length."
] |
Please provide a description of the function:def shuffle_and_batch_data(dataset,
target_names,
features_info,
training,
num_devices,
shuffle_buffer_size=1024,
... | [
"Shuffle and batch the given dataset.",
"Append targets to the example dictionary. Needed for Keras."
] |
Please provide a description of the function:def _train_and_eval_batches(dataset, data_dir, input_name, num_devices):
(train_data, eval_data, features_info, keys) = train_and_eval_dataset(
dataset, data_dir)
input_names, target_names = keys[0], keys[1]
train_batches = shuffle_and_batch_data(
train_... | [
"Return train and eval batches with input name and shape."
] |
Please provide a description of the function:def get_multi_dataset(datasets, pmf=None):
pmf = tf.fill([len(datasets)], 1.0 / len(datasets)) if pmf is None else pmf
samplers = [d.repeat().make_one_shot_iterator().get_next for d in datasets]
sample = lambda _: categorical_case(pmf, samplers)
return tf.data.Dat... | [
"Returns a Dataset that samples records from one or more Datasets.\n\n Args:\n datasets: A list of one or more Dataset objects to sample from.\n pmf: A tensor of shape [len(datasets)], the probabilities to sample each\n dataset with. This tensor is often constructed with the global_step. If\n this ... |
Please provide a description of the function:def get_schedule_distribution(schedule, global_step=None):
interpolation, steps, pmfs = schedule
if len(pmfs) == 1:
# py_func doesn't seem to work on TPU - at least get the constant case to
# run.
# TODO(noam): get the general case working.
return pmfs... | [
"Computes the pmf of a schedule given the global_step.\n\n Args:\n schedule: A schedule tuple, see encode_schedule for details.\n global_step: A scalar tensor, the step to query the schedule.\n\n Returns:\n A 1-D tensor of probs, the sampling distribution of the global_step.\n "
] |
Please provide a description of the function:def categorical_case(pmf, fns, rand=None):
rand = tf.random_uniform([]) if rand is None else rand
cmf = tf.pad(tf.cumsum(pmf), [(1, 0)])
cmf = [cmf[i] for i in range(len(fns) + 1)]
preds = [(rand >= a) & (rand < b) for a, b in zip(cmf[:-1], cmf[1:])]
return tf.c... | [
"Returns the outputs of fns[i] with probability pmf[i].\n\n Args:\n pmf: A 1-D tensor of probabilities, the probability mass function.\n fns: A list of callables that return tensors, same length as pmf.\n rand: An optional scalar between 0.0 and 1.0, the output of an RNG.\n\n Returns:\n A tensor, the ... |
Please provide a description of the function:def linear_interpolation(x, xp, fp, **kwargs):
yp = fp.reshape([fp.shape[0], -1]).transpose()
y = np.stack([np.interp(x, xp, zp, **kwargs) for zp in yp]).transpose()
return y.reshape(x.shape[:1] + fp.shape[1:]).astype(np.float32) | [
"Multi-dimensional linear interpolation.\n\n Returns the multi-dimensional piecewise linear interpolant to a function with\n given discrete data points (xp, fp), evaluated at x.\n\n Note that *N and *M indicate zero or more dimensions.\n\n Args:\n x: An array of shape [*N], the x-coordinates of the interpola... |
Please provide a description of the function:def step_interpolation(x, xp, fp, **kwargs):
del kwargs # Unused.
xp = np.expand_dims(xp, -1)
lower, upper = xp[:-1], xp[1:]
conditions = (x >= lower) & (x < upper)
# Underflow and overflow conditions and values. Values default to fp[0] and
# fp[-1] respectiv... | [
"Multi-dimensional step interpolation.\n\n Returns the multi-dimensional step interpolant to a function with\n given discrete data points (xp, fp), evaluated at x.\n\n Note that *N and *M indicate zero or more dimensions.\n\n Args:\n x: An array of shape [*N], the x-coordinates of the interpolated values.\n ... |
Please provide a description of the function:def epoch_rates_to_pmf(problems, epoch_rates=None):
if epoch_rates is None:
epoch_rates = [1.0] * len(problems)
example_rates = [epoch_rate * p.num_training_examples
for p, epoch_rate in zip(problems, epoch_rates)]
return example_rates_to_pmf(... | [
"Create a probability-mass-function based on relative epoch rates.\n\n if epoch_rates=None, then we use uniform epoch rates [1.0] * len(problems)\n i.e. it takes each problem the same time to go through one epoch.\n\n If epoch_rates is given, then these are the relative numbers of epochs\n of each problem to go... |
Please provide a description of the function:def encode_schedule(schedule):
interpolation, steps, pmfs = schedule
return interpolation + ' ' + ' '.join(
'@' + str(s) + ' ' + ' '.join(map(str, p)) for s, p in zip(steps, pmfs)) | [
"Encodes a schedule tuple into a string.\n\n Args:\n schedule: A tuple containing (interpolation, steps, pmfs), where\n interpolation is a string specifying the interpolation strategy, steps\n is an int array_like of shape [N] specifying the global steps, and pmfs is\n an array_like of shape [N, ... |
Please provide a description of the function:def decode_schedule(string):
splits = string.split()
steps = [int(x[1:]) for x in splits[1:] if x[0] == '@']
pmfs = np.reshape(
[float(x) for x in splits[1:] if x[0] != '@'], [len(steps), -1])
return splits[0], tuplize(steps), tuplize(pmfs) | [
"Decodes a string into a schedule tuple.\n\n Args:\n string: The string encoding of a schedule tuple.\n\n Returns:\n A schedule tuple, see encode_schedule for details.\n "
] |
Please provide a description of the function:def tuplize(nested):
if isinstance(nested, str):
return nested
try:
return tuple(map(tuplize, nested))
except TypeError:
return nested | [
"Recursively converts iterables into tuples.\n\n Args:\n nested: A nested structure of items and iterables.\n\n Returns:\n A nested structure of items and tuples.\n "
] |
Please provide a description of the function:def filepattern(self, *args, **kwargs):
return [p.filepattern(*args, **kwargs) for p in self.problems] | [
"Returns a list of filepatterns, one for each problem."
] |
Please provide a description of the function:def generate_data(self, *args, **kwargs):
for p in self.problems:
p.generate_data(*args, **kwargs) | [
"Generates data for each problem."
] |
Please provide a description of the function:def dataset(self, mode, hparams=None, global_step=None, **kwargs):
datasets = [p.dataset(mode, **kwargs) for p in self.problems]
datasets = [
d.map(lambda x, i=j: self.normalize_example( # pylint: disable=g-long-lambda
dict(x, problem_id=tf.... | [
"Returns a dataset containing examples from multiple problems.\n\n Args:\n mode: A member of problem.DatasetSplit.\n hparams: A tf.HParams object, the model hparams.\n global_step: A scalar tensor used to compute the sampling distribution.\n If global_step is None, we call tf.train.get_or_c... |
Please provide a description of the function:def normalize_example(self, example, hparams):
length = self.max_length(hparams)
def _to_constant_shape(tensor):
tensor = tensor[:length]
tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])])
return tf.reshape(tensor, [length])
if ... | [
"Assumes that example contains both inputs and targets."
] |
Please provide a description of the function:def generate_data_with_shared_vocab(self, data_dir, tmp_dir, task_id=-1):
global_vocab_filename = os.path.join(data_dir, self.vocab_filename)
if not tf.gfile.Exists(global_vocab_filename):
raise ValueError(
'Global vocabulary file: %s does not ex... | [
"Generates TF-Records for problems using a global vocabulary file."
] |
Please provide a description of the function:def lengths_to_area_mask(feature_length, length, max_area_size):
paddings = tf.cast(tf.expand_dims(
tf.logical_not(
tf.sequence_mask(feature_length, maxlen=length)), 2), tf.float32)
_, _, area_sum, _, _ = compute_area_features(paddings,
... | [
"Generates a non-padding mask for areas based on lengths.\n\n Args:\n feature_length: a tensor of [batch_size]\n length: the length of the batch\n max_area_size: the maximum area size considered\n Returns:\n mask: a tensor in shape of [batch_size, num_areas]\n "
] |
Please provide a description of the function:def _pool_one_shape(features_2d, area_width, area_height, batch_size,
width, height, depth, fn=tf.reduce_max, name=None):
with tf.name_scope(name, default_name="pool_one_shape"):
images = []
for y_shift in range(area_height):
image_heig... | [
"Pools for an area in features_2d.\n\n Args:\n features_2d: a Tensor in a shape of [batch_size, height, width, depth].\n area_width: the max width allowed for an area.\n area_height: the max height allowed for an area.\n batch_size: the batch size.\n width: the width of the memory.\n height: the ... |
Please provide a description of the function:def basic_pool(features, max_area_width, max_area_height=1, height=1,
fn=tf.reduce_max, name=None):
with tf.name_scope(name, default_name="basic_pool"):
feature_shape = common_layers.shape_list(features)
batch_size = feature_shape[0]
length = ... | [
"Pools for each area based on a given pooling function (fn).\n\n Args:\n features: a Tensor in a shape of [batch_size, height * width, depth].\n max_area_width: the max width allowed for an area.\n max_area_height: the max height allowed for an area.\n height: the height of the image.\n fn: the TF f... |
Please provide a description of the function:def _compute_sum_image(features, max_area_width, max_area_height=1, height=1,
name=None):
with tf.name_scope(name, default_name="compute_sum_image"):
feature_shape = common_layers.shape_list(features)
batch_size = feature_shape[0]
leng... | [
"Computes area sums for features.\n\n Args:\n features: a Tensor in a shape of [batch_size, height * width, depth].\n max_area_width: the max width allowed for an area.\n max_area_height: the max height allowed for an area.\n height: the height of the image.\n name: the namescope.\n Returns:\n s... |
Please provide a description of the function:def compute_area_features(features, max_area_width, max_area_height=1, height=1,
epsilon=1e-6):
with tf.name_scope("compute_area_features"):
tf.logging.info("area_attention compute_area_features: %d x %d",
max_area_heigh... | [
"Computes features for each area.\n\n Args:\n features: a Tensor in a shape of [batch_size, height * width, depth].\n max_area_width: the max width allowed for an area.\n max_area_height: the max height allowed for an area.\n height: the height of the image.\n epsilon: the epsilon added to the varia... |
Please provide a description of the function:def compute_area_key(features, max_area_width, max_area_height=1, height=1,
mode="mean", training=True, name=None):
tf.logging.info("area_attention mode=%s", mode)
area_mean, area_std, _, area_heights, area_widths =\
compute_area_features(f... | [
"Computes the key for each area.\n\n Args:\n features: a Tensor in a shape of [batch_size, height * width, depth].\n max_area_width: the max width allowed for an area.\n max_area_height: the max height allowed for an area.\n height: the height of the image.\n mode: whether to combine different area ... |
Please provide a description of the function:def dot_product_area_attention(q,
k,
v,
bias,
dropout_rate=0.0,
image_shapes=None,
name=N... | [
"Dot-product area attention.\n\n Args:\n q: Tensor with shape [..., length_q, depth_k].\n k: Tensor with shape [..., length_kv, depth_k]. Leading dimensions must\n match with q.\n v: Tensor with shape [..., length_kv, depth_v] Leading dimensions must\n match with q.\n bias: bias Tensor (see a... |
Please provide a description of the function:def setup_directories(base_dir, subdirs):
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
... | [
"Setup directories."
] |
Please provide a description of the function:def make_relative_timing_fn():
start_time = time.time()
def format_relative_time():
time_delta = time.time() - start_time
return str(datetime.timedelta(seconds=time_delta))
def log_relative_time():
tf.logging.info("Timing: %s", format_relative_time())
... | [
"Make a function that logs the duration since it was made."
] |
Please provide a description of the function:def train_supervised(problem, model_name, hparams, data_dir, output_dir,
train_steps, eval_steps, local_eval_frequency=None,
schedule="continuous_train_and_eval"):
if local_eval_frequency is None:
local_eval_frequency = FLAG... | [
"Train supervised."
] |
Please provide a description of the function:def train_agent(real_env, learner, world_model_dir, hparams, epoch):
initial_frame_chooser = rl_utils.make_initial_frame_chooser(
real_env, hparams.frame_stack_size, hparams.simulation_random_starts,
hparams.simulation_flip_first_random_for_beginning
)
e... | [
"Train the PPO agent in the simulated environment."
] |
Please provide a description of the function:def train_agent_real_env(env, learner, hparams, epoch):
base_algo_str = hparams.base_algo
train_hparams = trainer_lib.create_hparams(hparams.base_algo_params)
rl_utils.update_hparams_from_hparams(
train_hparams, hparams, "real_" + base_algo_str + "_"
)
if... | [
"Train the PPO agent in the real environment."
] |
Please provide a description of the function:def train_world_model(
env, data_dir, output_dir, hparams, world_model_steps_num, epoch
):
world_model_steps_num += world_model_step_increment(
hparams, is_initial_epoch=(epoch == 0)
)
model_hparams = trainer_lib.create_hparams(hparams.generative_model_par... | [
"Train the world model on problem_name."
] |
Please provide a description of the function:def load_metrics(event_dir, epoch):
metrics = {}
for filename in tf.gfile.ListDirectory(event_dir):
path = os.path.join(event_dir, filename)
for event in tf.train.summary_iterator(path):
if event.step == epoch and event.HasField("summary"):
value... | [
"Loads metrics for this epoch if they have already been written.\n\n This reads the entire event file but it's small with just per-epoch metrics.\n\n Args:\n event_dir: TODO(koz4k): Document this.\n epoch: TODO(koz4k): Document this.\n\n Returns:\n metrics.\n "
] |
Please provide a description of the function:def training_loop(hparams, output_dir, report_fn=None, report_metric=None):
if report_fn:
assert report_metric is not None
# Directories
subdirectories = [
"data", "tmp", "world_model", ("world_model", "debug_videos"),
"policy", "eval_metrics"
]
... | [
"Run the main training loop."
] |
Please provide a description of the function:def conv_layer(x,
hidden_size,
kernel_size,
stride,
pooling_window,
dropout_rate,
dilation_rate,
name="conv"):
with tf.variable_scope(name):
out = x
out = co... | [
"Single conv layer with relu, optional pooling, and dropout."
] |
Please provide a description of the function:def gene_expression_conv_base():
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.batch_size = input_length * batch_si... | [
"Hparams for GeneExpressionConv model."
] |
Please provide a description of the function:def compress_self_attention_layer(x, hparams, name=None):
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, hpara... | [
"Attend function."
] |
Please provide a description of the function:def compute_nats_and_bits_per_dim(data_dim,
latent_dim,
average_reconstruction,
average_prior):
with tf.name_scope(None, default_name="compute_nats_per_dim"):
data_... | [
"Computes negative ELBO, which is an upper bound on the negative likelihood.\n\n Args:\n data_dim: int-like indicating data dimensionality.\n latent_dim: int-like indicating latent dimensionality.\n average_reconstruction: Scalar Tensor indicating the reconstruction cost\n averaged over all data dime... |
Please provide a description of the function:def multinomial_sample(x, vocab_size=None, sampling_method="random",
temperature=1.0):
vocab_size = vocab_size or common_layers.shape_list(x)[-1]
if sampling_method == "random" and temperature > 0.0:
samples = tf.multinomial(tf.reshape(x, [-... | [
"Multinomial sampling from a n-dimensional tensor.\n\n Args:\n x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial.\n vocab_size: Number of classes in multinomial distribution.\n sampling_method: String, \"random\" or otherwise deterministic.\n temperature: Positive float.\n\n Re... |
Please provide a description of the function:def ae_latent_softmax(latents_pred, latents_discrete_hot, vocab_size, hparams):
with tf.variable_scope("latent_logits"):
latents_logits = tf.layers.dense(latents_pred, vocab_size,
name="logits_dense")
if hparams.logit_normali... | [
"Latent prediction and loss.\n\n Args:\n latents_pred: Tensor of shape [..., depth].\n latents_discrete_hot: Tensor of shape [..., vocab_size].\n vocab_size: an int representing the vocab size.\n hparams: HParams.\n\n Returns:\n sample: Tensor of shape [...], a sample from a multinomial distributio... |
Please provide a description of the function:def ae_latent_sample_beam(latents_dense_in, inputs, ed, embed, hparams):
def symbols_to_logits_fn(ids):
ids = tf.expand_dims(ids, axis=2) # Ids start with added all-zeros.
latents_discrete = tf.pad(ids[:, 1:], [[0, 0], [0, 1], [0, 0]])
with tf.variab... | [
"Samples from the latent space in the autoencoder.\n\n Args:\n latents_dense_in: Tensor of shape [batch, length_q, ...]. Only the shape of\n its first two dimensions are used. length_q is the latent length, which is\n height * width * hparams.num_latents / (2**hparams.num_compress_steps).\n inputs:... |
Please provide a description of the function:def residual_block_layer(inputs, hparams):
kernel = (hparams.res_kernel_size, hparams.res_kernel_size)
x = inputs
for i in range(hparams.num_res_layers):
with tf.variable_scope("res_conv_%d" % i):
# kernel_size x kernel_size conv block
y = common_lay... | [
"Residual block over inputs.\n\n Runs a residual block consisting of\n conv: kernel_size x kernel_size\n conv: 1x1\n dropout, add and normalize according to hparams.layer_postprocess_sequence.\n\n Args:\n inputs: Tensor of shape [batch, height, width, hparams.hidden_size].\n hparams: HParams.\n\n ... |
Please provide a description of the function:def compress_encoder(inputs,
hparams,
strides=(2, 2),
kernel_size=(3, 3),
name=None):
with tf.variable_scope(name, default_name="compress"):
x = inputs
for i in range(hparams.num... | [
"Encoder that compresses 2-D inputs by 2**num_compress_steps.\n\n Args:\n inputs: Tensor of shape [batch, height, width, channels].\n hparams: HParams.\n strides: Tuple, strides for conv block.\n kernel_size: Tuple, kernel window size for conv block.\n name: string, variable scope.\n\n Returns:\n ... |
Please provide a description of the function:def compress_encoder_2d(x, hparams, name=None):
return compress_encoder(
x,
hparams,
strides=(2, 2),
kernel_size=(hparams.kernel_size, hparams.kernel_size),
name=name) | [
"Encoder that compresses 2-D inputs by 2**num_compress_steps.\n\n Args:\n x: Tensor of shape [batch, height, width, channels].\n hparams: HParams.\n name: string, variable scope.\n\n Returns:\n Tensor of shape [batch, latent_length, hparams.hidden_size], where\n latent_length is\n hparams.nu... |
Please provide a description of the function:def compress_encoder_1d(x, hparams, name=None):
x = tf.expand_dims(x, axis=2)
return compress_encoder(x,
hparams,
strides=(2, 1),
kernel_size=(hparams.kernel_size, 1),
... | [
"Encoder that compresses 1-D inputs by 2**num_compress_steps.\n\n Args:\n x: Tensor of shape [batch, length, channels].\n hparams: HParams.\n name: string, variable scope.\n\n Returns:\n Tensor of shape [batch, latent_length, hparams.hidden_size], where\n latent_length is\n hparams.num_laten... |
Please provide a description of the function:def decompress_decoder(inputs,
hparams,
strides=(2, 2),
kernel=(3, 3),
name=None):
with tf.variable_scope(name, default_name="decompress"):
x = inputs
x = tf.layers.dense... | [
"Decoder that decompresses 2-D inputs by 2**num_compress_steps.\n\n Args:\n inputs: Tensor of shape [batch, compress_height, compress_width, channels].\n hparams: HParams.\n strides: Tuple, strides for conv block.\n kernel: Tuple, kernel window size for conv block.\n name: string, variable scope.\n\... |
Please provide a description of the function:def decompress_decoder_2d(x, hparams, name=None):
return decompress_decoder(x, hparams,
strides=(2, 2),
kernel=(hparams.kernel_size, hparams.kernel_size),
name=name) | [
"Decoder that decompresses 2-D inputs by 2**num_compress_steps.\n\n Args:\n x: Tensor of shape [batch, compress_height, compress_width, channels].\n hparams: HParams.\n name: string, variable scope.\n\n Returns:\n Tensor of shape [batch, height, width, hparams.hidden_size].\n "
] |
Please provide a description of the function:def decompress_decoder_1d(x, hparams, name=None):
x = tf.expand_dims(x, axis=2)
output = decompress_decoder(x, hparams,
strides=(2, 1),
kernel=(hparams.kernel_size, 1),
name=name... | [
"Decoder that decompresses 1-D inputs by 2**num_compress_steps.\n\n Args:\n x: Tensor of shape [batch, compress_length, channels].\n hparams: HParams.\n name: string, variable scope.\n\n Returns:\n Tensor of shape [batch, length, hparams.hidden_size].\n "
] |
Please provide a description of the function:def transformer_text_encoder(inputs,
target_space,
hparams,
name=None):
with tf.variable_scope(name, default_name="transformer_text_encoder"):
inputs = common_layers.flatten4d3d(i... | [
"Transformer text encoder over inputs with unmasked full attention.\n\n Args:\n inputs: Tensor of shape [batch, length, 1, hparams.hidden_size].\n target_space: int. Used for encoding inputs under a target space id.\n hparams: HParams.\n name: string, variable scope.\n\n Returns:\n encoder_output: ... |
Please provide a description of the function:def transformer_image_decoder(targets,
encoder_output,
ed_attention_bias,
hparams,
name=None):
with tf.variable_scope(name, default_name="transformer_... | [
"Transformer image decoder over targets with local attention.\n\n Args:\n targets: Tensor of shape [batch, ...], and whose size is batch * height *\n width * hparams.num_channels * hparams.hidden_size.\n encoder_output: Tensor of shape [batch, length_kv, hparams.hidden_size].\n ed_attention_bias: Ten... |
Please provide a description of the function:def transformer_latent_decoder(x,
encoder_output,
ed_attention_bias,
hparams,
name=None):
with tf.variable_scope(name, default_name="transformer_l... | [
"Transformer decoder over latents using latent_attention_type.\n\n Args:\n x: Tensor of shape [batch, length_q, hparams.hidden_size]. length_q is the\n latent length, which is\n height * width * hparams.num_latents / (2**hparams.num_compress_steps).\n encoder_output: Tensor of shape [batch, length_... |
Please provide a description of the function:def bottleneck_layer(inputs,
hparams,
name="discrete_bottleneck"):
[
latents_dense,
latents_discrete,
extra_loss,
embed_fn,
_,
] = hparams.bottleneck(inputs=inputs,
filter... | [
"Computes latents given inputs (typically, compressed targets)."
] |
Please provide a description of the function:def latent_prediction_model(inputs,
ed_attention_bias,
latents_discrete,
latents_dense,
hparams,
vocab_size=None,
... | [
"Transformer-based latent prediction model.\n\n It is an autoregressive decoder over latents_discrete given inputs.\n\n Args:\n inputs: Tensor of shape [batch, length_kv, hparams.hidden_size]. Inputs to\n attend to for the decoder on latents.\n ed_attention_bias: Tensor which broadcasts with shape [bat... |
Please provide a description of the function:def transformer_autoencoder(inputs,
targets,
target_space,
hparams,
cache=None,
predict_mask=1.0):
original_targets_shape = common... | [
"Auto-encoder using a Transformer decoder and a prior over latent sequences.\n\n Args:\n inputs: Tensor of shape [batch, length, 1, hparams.hidden_size] or None.\n targets: Tensor of shape [batch, ..., channels]. Ellipses may be 1 or 2\n dimensions denoting sequence length.\n target_space: int. Used ... |
Please provide a description of the function:def iaf_flow(one_hot_assignments,
scale_weights,
scale_bias,
num_codes,
summary=True,
name=None):
with tf.name_scope(name, default_name="iaf"):
# Pad the one_hot_assignments by zeroing out the first la... | [
"Performs a single IAF flow using scale and normalization transformations.\n\n Args:\n one_hot_assignments: Assignments Tensor with shape [num_samples, batch_size,\n latent_size, num_codes].\n scale_weights: Tensor corresponding to lower triangular matrix used to\n autoregressively generate scale m... |
Please provide a description of the function:def _get_lsun(directory, category, split_name):
generator_utils.maybe_download(directory,
_LSUN_DATA_FILENAME % (category, split_name),
_LSUN_URL % (category, split_name)) | [
"Downloads all lsun files to directory unless they are there."
] |
Please provide a description of the function:def _mixed_precision_is_enabled(hparams):
activation_dtype = hparams.activation_dtype
weight_dtype = hparams.weight_dtype
return activation_dtype == tf.float16 and weight_dtype == tf.float32 | [
"Should be the same as in common_attention, avoiding import."
] |
Please provide a description of the function:def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None):
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 vari... | [
"Minimize loss."
] |
Please provide a description of the function:def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None):
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]
weight_decay_loss = weight_decay(hpa... | [
"Apply weight decay and weight noise."
] |
Please provide a description of the function:def weight_noise(noise_rate, learning_rate, 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_ops = []
for v in var_list:
with tf.... | [
"Apply weight noise to vars in var_list."
] |
Please provide a description of the function:def weight_decay(decay_rate, var_list, skip_biases=True):
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.
# This is a heuristic way to detect b... | [
"Apply weight decay to vars in var_list."
] |
Please provide a description of the function:def log_variable_sizes(var_list=None, tag=None, verbose=False):
if var_list is None:
var_list = tf.trainable_variables()
if tag is None:
tag = "Trainable Variables"
if not var_list:
return
name_to_var = {v.name: v for v in var_list}
total_size = 0
... | [
"Log the sizes and shapes of variables, and the total size.\n\n Args:\n var_list: a list of variables; defaults to trainable_variables\n tag: a string; defaults to \"Trainable Variables\"\n verbose: bool, if True, log every weight; otherwise, log total size only.\n "
] |
Please provide a description of the function:def summarize_variables(var_list=None, tag=None):
if var_list is None:
var_list = tf.trainable_variables()
if tag is None:
tag = "training_variables/"
name_to_var = {v.name: v for v in var_list}
for v_name in list(name_to_var):
v = name_to_var[v_name]... | [
"Summarize the variables.\n\n Args:\n var_list: a list of variables; defaults to trainable_variables.\n tag: name scope of the summary; defaults to training_variables/.\n "
] |
Please provide a description of the function:def get_variable_initializer(hparams):
if not hparams.initializer:
return None
mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN,
value=hparams.initializer_gain,
hparams=hparams)
... | [
"Get variable initializer from hparams."
] |
Please provide a description of the function:def summarize_tensors(tensor_dict, tag=None):
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag + t_name, t) | [
"Summarize the tensors.\n\n Args:\n tensor_dict: a dictionary of tensors.\n tag: name scope of the summary; defaults to tensors/.\n "
] |
Please provide a description of the function: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_epsilon=1e-5,... | [
"Extract image features from pretrained resnet model."
] |
Please provide a description of the function:def multihead_attention(query_antecedent,
memory_antecedent,
bias,
total_key_depth,
total_value_depth,
output_depth,
num_heads,
... | [
"Multihead scaled-dot-product attention with input/output transformations.\n\n Args:\n query_antecedent: a Tensor with shape [batch, length_q, channels]\n memory_antecedent: a Tensor with shape [batch, length_m, channels] or None\n bias: bias Tensor (see attention_bias())\n total_key_depth: an integer\... |
Please provide a description of the function:def _get_timit(directory):
if os.path.exists(os.path.join(directory, "timit")):
return
assert FLAGS.timit_paths
for path in FLAGS.timit_paths.split(","):
with tf.gfile.GFile(path) as f:
with tarfile.open(fileobj=f, mode="r:gz") as timit_compressed:
... | [
"Extract TIMIT datasets to directory unless directory/timit exists."
] |
Please provide a description of the function:def _collect_data(directory, input_ext, target_ext):
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the datafile was "/path/to/datafile.wav" then the key would be
# "/path/to/... | [
"Traverses directory collecting input and target files."
] |
Please provide a description of the function:def timit_generator(data_dir,
tmp_dir,
training,
how_many,
start_from=0,
eos_list=None,
vocab_filename=None,
vocab_size=0):
del da... | [
"Data generator for TIMIT transcription problem.\n\n Args:\n data_dir: path to the data directory.\n tmp_dir: path to temporary storage directory.\n training: a Boolean; if true, we use the train set, otherwise the test set.\n how_many: how many inputs and labels to generate.\n start_from: from whic... |
Please provide a description of the function:def _build_vocab(filename, vocab_dir, vocab_name):
vocab_path = os.path.join(vocab_dir, vocab_name)
if not tf.gfile.Exists(vocab_path):
with tf.gfile.GFile(filename, "r") as f:
data = f.read().split()
counter = collections.Counter(data)
count_pairs =... | [
"Reads a file to build a vocabulary.\n\n Args:\n filename: file to read list of words from.\n vocab_dir: directory where to save the vocabulary.\n vocab_name: vocab file name.\n\n Returns:\n text encoder.\n "
] |
Please provide a description of the function:def _maybe_download_corpus(tmp_dir, vocab_type):
if vocab_type == text_problems.VocabType.CHARACTER:
dataset_url = ("https://s3.amazonaws.com/research.metamind.io/wikitext"
"/wikitext-103-raw-v1.zip")
dir_name = "wikitext-103-raw"
else:
... | [
"Download and unpack the corpus.\n\n Args:\n tmp_dir: directory containing dataset.\n vocab_type: which vocabulary are we using.\n\n Returns:\n The list of names of files.\n "
] |
Please provide a description of the function:def get_batch_coordinate(x):
# Compute the batch coordinate before flattening all batches
batch_coordinate = tf.expand_dims(
common_attention.coordinate_tensor(
common_layers.shape_list(x)[:-1], axis=0),
axis=-1)
return batch_coordinate | [
"Return a flat int32 tensor of shape [1, batch_size*length, 1]."
] |
Please provide a description of the function:def aligned_base():
hparams = common_hparams.basic_params1()
hparams.hidden_size = 512
hparams.batch_size = 5000
hparams.max_length = 0
hparams.min_length_bucket = 1024
hparams.dropout = 0.0
hparams.layer_prepostprocess_dropout = 0.0
hparams.label_smoothin... | [
"Set of hyperparameters.\n\n languagemodel_wiki_scramble1k50, 1gpu, 7k steps (10min): log(ppl)_eval = 2.60\n 12.0 steps/sec on P100\n 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.00\n\n Returns:\n a hparams object\n "
] |
Please provide a description of the function:def aligned_8k_grouped():
hparams = aligned_grouped()
hparams.batch_size = 8192
# hparams.attention_image_summary = False
hparams.num_groups = 16
hparams.multiplicative_overhead = 1.1
return hparams | [
"version for languagemodel_wiki_scramble8k50.\n\n languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92\n 3.3 steps/sec on P100\n 8gpu (8x batch), 7k steps: log(ppl)_eval = 2.15\n\n Returns:\n a hparams object\n "
] |
Please provide a description of the function:def _merge_beam_dim(tensor):
shape = common_layers.shape_list(tensor)
shape[0] *= shape[1] # batch -> batch * beam_size
shape.pop(1) # Remove beam dim
return tf.reshape(tensor, shape) | [
"Reshapes first two dimensions in to single dimension.\n\n Args:\n tensor: Tensor to reshape of shape [A, B, ...]\n\n Returns:\n Reshaped tensor of shape [A*B, ...]\n "
] |
Please provide a description of the function:def _unmerge_beam_dim(tensor, batch_size, beam_size):
shape = common_layers.shape_list(tensor)
new_shape = [batch_size] + [beam_size] + shape[1:]
return tf.reshape(tensor, new_shape) | [
"Reshapes first dimension back to [batch_size, beam_size].\n\n Args:\n tensor: Tensor to reshape of shape [batch_size*beam_size, ...]\n batch_size: Tensor, original batch size.\n beam_size: int, original beam size.\n\n Returns:\n Reshaped tensor of shape [batch_size, beam_size, ...]\n "
] |
Please provide a description of the function:def _expand_to_beam_size(tensor, beam_size):
tensor = tf.expand_dims(tensor, axis=1)
tile_dims = [1] * tensor.shape.ndims
tile_dims[1] = beam_size
return tf.tile(tensor, tile_dims) | [
"Tiles a given tensor by beam_size.\n\n Args:\n tensor: tensor to tile [batch_size, ...]\n beam_size: How much to tile the tensor by.\n\n Returns:\n Tiled tensor [batch_size, beam_size, ...]\n "
] |
Please provide a description of the function:def get_state_shape_invariants(tensor):
shape = tensor.shape.as_list()
for i in range(1, len(shape) - 1):
shape[i] = None
return tf.TensorShape(shape) | [
"Returns the shape of the tensor but sets middle dims to None."
] |
Please provide a description of the function:def compute_batch_indices(batch_size, beam_size):
batch_pos = tf.range(batch_size * beam_size) // beam_size
batch_pos = tf.reshape(batch_pos, [batch_size, beam_size])
return batch_pos | [
"Computes the i'th coordinate that contains the batch index for gathers.\n\n Batch pos is a tensor like [[0,0,0,0,],[1,1,1,1],..]. It says which\n batch the beam item is in. This will create the i of the i,j coordinate\n needed for the gather.\n\n Args:\n batch_size: Batch size\n beam_size: Size of the be... |
Please provide a description of the function:def fast_tpu_gather(params, indices, name=None):
with tf.name_scope(name):
dtype = params.dtype
def _gather(params, indices):
if dtype != tf.float32:
params = tf.to_float(params)
shape = common_layers.shape_list(params)
indices_... | [
"Fast gather implementation for models running on TPU.\n\n This function use one_hot and batch matmul to do gather, which is faster\n than gather_nd on TPU. For params that have dtype of int32 (sequences to\n gather from), batch_gather is used to keep accuracy.\n\n Args:\n params: A tensor from which to gath... |
Please provide a description of the function:def _create_make_unique(inputs):
if inputs.shape.ndims != 2:
raise ValueError("Input of top_k_with_unique must be rank-2 "
"but got: %s" % inputs.shape)
height = inputs.shape[0]
width = inputs.shape[1]
zeros = tf.zeros([height, width], dt... | [
"Replaces the lower bits of each element with iota.\n\n The iota is used to derive the index, and also serves the purpose to\n make each element unique to break ties.\n\n Args:\n inputs: A tensor with rank of 2 and dtype of tf.float32.\n [batch_size, original_size].\n\n Returns:\n A tensor after elem... |
Please provide a description of the function:def _create_topk_unique(inputs, k):
height = inputs.shape[0]
width = inputs.shape[1]
neg_inf_r0 = tf.constant(-np.inf, dtype=tf.float32)
ones = tf.ones([height, width], dtype=tf.float32)
neg_inf_r2 = ones * neg_inf_r0
inputs = tf.where(tf.is_nan(inputs), neg_i... | [
"Creates the top k values in sorted order with indices.\n\n Args:\n inputs: A tensor with rank of 2. [batch_size, original_size].\n k: An integer, number of top elements to select.\n\n Returns:\n topk_r2: A tensor, the k largest elements. [batch_size, k].\n topk_indices_r2: A tensor, indices of the to... |
Please provide a description of the function:def top_k_with_unique(inputs, k):
unique_inputs = _create_make_unique(tf.cast(inputs, tf.float32))
top_values, indices = _create_topk_unique(unique_inputs, k)
top_values = tf.cast(top_values, inputs.dtype)
return top_values, indices | [
"Finds the values and indices of the k largests entries.\n\n Instead of doing sort like tf.nn.top_k, this function finds the max value\n k times. The running time is proportional to k, which is be faster when k\n is small. The current implementation supports only inputs of rank 2.\n In addition, iota is used to... |
Please provide a description of the function:def compute_topk_scores_and_seq(sequences,
scores,
scores_to_gather,
flags,
beam_size,
batch_size,
... | [
"Given sequences and scores, will gather the top k=beam size sequences.\n\n This function is used to grow alive, and finished. It takes sequences,\n scores, and flags, and returns the top k from sequences, scores_to_gather,\n and flags based on the values in scores.\n\n This method permits easy introspection us... |
Please provide a description of the function:def beam_search(symbols_to_logits_fn,
initial_ids,
beam_size,
decode_length,
vocab_size,
alpha,
states=None,
eos_id=EOS_ID,
stop_early=True,
... | [
"Beam search with length penalties.\n\n Requires a function that can take the currently decoded symbols and return\n the logits for the next symbol. The implementation is inspired by\n https://arxiv.org/abs/1609.08144.\n\n When running, the beam search steps can be visualized by using tfdbg to watch\n the oper... |
Please provide a description of the function:def video_augmentation(features, hue=False, saturate=False, contrast=False):
inputs, targets = features["inputs"], features["targets"]
in_steps = common_layers.shape_list(inputs)[0]
# makes sure that the same augmentation is applied to both input and targets.
# i... | [
"Augments video with optional hue, saturation and constrast.\n\n Args:\n features: dict, with keys \"inputs\", \"targets\".\n features[\"inputs\"], 4-D Tensor, shape=(THWC)\n features[\"targets\"], 4-D Tensor, shape=(THWC)\n hue: bool, apply hue_transform.\n saturate: bool, apply... |
Please provide a description of the function:def create_border(video, color="blue", border_percent=2):
# Do not create border if the video is not in RGB format
if video.shape[-1] != 3:
return video
color_to_axis = {"blue": 2, "red": 0, "green": 1}
axis = color_to_axis[color]
_, _, height, width, _ = vi... | [
"Creates a border around each frame to differentiate input and target.\n\n Args:\n video: 5-D NumPy array.\n color: string, \"blue\", \"red\" or \"green\".\n border_percent: Percentarge of the frame covered by the border.\n Returns:\n video: 5-D NumPy array.\n "
] |
Please provide a description of the function:def convert_videos_to_summaries(input_videos, output_videos, target_videos,
tag, decode_hparams,
display_ground_truth=False):
fps = decode_hparams.frames_per_second
border_percent = decode_hparams.border_... | [
"Converts input, output and target videos into video summaries.\n\n Args:\n input_videos: 5-D NumPy array, (NTHWC) conditioning frames.\n output_videos: 5-D NumPy array, (NTHWC) model predictions.\n target_videos: 5-D NumPy array, (NTHWC) target frames.\n tag: tf summary tag.\n decode_hparams: HPara... |
Please provide a description of the function:def display_video_hooks(hook_args):
predictions = hook_args.predictions
max_outputs = hook_args.decode_hparams.max_display_outputs
max_decodes = hook_args.decode_hparams.max_display_decodes
with tf.Graph().as_default():
_, best_decodes = video_metrics.compute... | [
"Hooks to display videos at decode time."
] |
Please provide a description of the function:def summarize_video_metrics(hook_args):
problem_name = hook_args.problem.name
current_problem = hook_args.problem
hparams = hook_args.hparams
output_dirs = hook_args.output_dirs
predictions = hook_args.predictions
frame_shape = [
current_problem.frame_he... | [
"Computes video metrics summaries using the decoder output."
] |
Please provide a description of the function:def debug_video_writer_factory(output_dir):
if FLAGS.disable_ffmpeg:
return common_video.IndividualFrameWriter(output_dir)
else:
output_path = os.path.join(output_dir, "video.avi")
return common_video.WholeVideoWriter(
fps=10, output_path=output_pa... | [
"Creates a VideoWriter for debug videos."
] |
Please provide a description of the function:def preprocess_example(self, example, mode, hparams):
if getattr(hparams, "preprocess_resize_frames", None) is not None:
example["frame"] = tf.image.resize_images(
example["frame"], hparams.preprocess_resize_frames,
tf.image.ResizeMethod.BI... | [
"Runtime preprocessing, e.g., resize example[\"frame\"]."
] |
Please provide a description of the function:def serving_input_fn(self, hparams):
video_input_frames = tf.placeholder(
dtype=tf.float32,
shape=[
None, hparams.video_num_input_frames, self.frame_width,
self.frame_height, self.num_channels
])
# TODO(michalski)... | [
"For serving/predict, assume that only video frames are provided."
] |
Please provide a description of the function:def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
writer = None
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(None, None, None))
encoded_image_t = tf.image.encode_png(image_t)
with tf.Session... | [
"Generate samples of the encoded frames with possible extra data.\n\n By default this function just encodes the numpy array returned as \"frame\"\n from `self.generate_samples` into a PNG image. Override this function to\n get other encodings on disk.\n\n Args:\n data_dir: final data directory. Typ... |
Please provide a description of the function:def generate_data(self, data_dir, tmp_dir, task_id=-1):
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.DatasetSplit.EVAL: self.dev_filepaths,
problem.DatasetSplit.TEST: self.test_filepaths,
}
# We set s... | [
"The function generating the data."
] |
Please provide a description of the function:def add_scope(scope=None, scope_fn=None):
def decorator(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
name = kwargs.pop("name", None) # Python 2 hack for keyword only args
with scope_fn(name or scope or f.__name__):
return f(*args... | [
"Return a decorator which add a TF name/variable scope to a function.\n\n Note that the function returned by the decorator accept an additional 'name'\n parameter, which can overwrite the name scope given when the function is\n created.\n\n Args:\n scope (str): name of the scope. If None, the function name i... |
Please provide a description of the function:def _add_variable_proxy_methods(var, proxy_tensor):
proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)
proxy_tensor.assign_sub = var.assign_sub
proxy_tensor.assign = var.assign
proxy_tensor.initialized_value = var.initialized_value | [
"Proxy methods of underlying variable.\n\n This enables our custom getters to still work with, e.g., batch norm.\n\n Args:\n var: Variable to proxy\n proxy_tensor: Tensor that is identity of var\n "
] |
Please provide a description of the function:def _rowwise_unsorted_segment_sum(values, indices, n):
batch, k = tf.unstack(tf.shape(indices), num=2)
indices_flat = tf.reshape(indices, [-1]) + tf.div(tf.range(batch * k), k) * n
ret_flat = tf.unsorted_segment_sum(
tf.reshape(values, [-1]), indices_flat, bat... | [
"UnsortedSegmentSum on each row.\n\n Args:\n values: a `Tensor` with shape `[batch_size, k]`.\n indices: an integer `Tensor` with shape `[batch_size, k]`.\n n: an integer.\n Returns:\n A `Tensor` with the same type as `values` and shape `[batch_size, n]`.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.