Search is not available for this dataset
text stringlengths 75 104k |
|---|
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... |
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... |
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:... |
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... |
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_... |
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
... |
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... |
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... |
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... |
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... |
def image_question_encoder(encoder_inputs,
encoder_self_attention_bias,
hparams,
query=None,
name="image_question_encoder",
save_weights_to=None,
make_image_s... |
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... |
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):
... |
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 = ... |
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... |
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 |
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... |
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,
... |
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... |
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:
... |
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_... |
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... |
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... |
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... |
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... |
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... |
def linear_interpolate(tensor1, tensor2, coeffs):
"""Linearly interpolate between two tensors at coeff.
Args:
tensor1: 4-D Tensor, shape=(NHWC)
tensor2: 4-D Tensor, shape=(NHWC)
coeffs: list of floats.
Returns:
interp_latents: 5-D Tensor, with interp_latents[i] representing
in... |
def linear_interpolate_rank(tensor1, tensor2, coeffs, rank=1):
"""Linearly interpolate channel at "rank" between two tensors.
The channels are ranked according to their L2 norm between tensor1[channel]
and tensor2[channel].
Args:
tensor1: 4-D Tensor, NHWC
tensor2: 4-D Tensor, NHWC
coeffs: list of ... |
def postprocess(x, n_bits_x=8):
"""Converts x from [-0.5, 0.5], to [0, 255].
Args:
x: 3-D or 4-D Tensor normalized between [-0.5, 0.5]
n_bits_x: Number of bits representing each pixel of the output.
Defaults to 8, to default to 256 possible values.
Returns:
x: 3-D or 4-D Tensor represen... |
def get_cond_latents_at_level(cond_latents, level, hparams):
"""Returns a single or list of conditional latents at level 'level'."""
if cond_latents:
if hparams.latent_dist_encoder in ["conv_net", "conv3d_net"]:
return [cond_latent[level] for cond_latent in cond_latents]
elif hparams.latent_dist_encod... |
def check_cond_latents(cond_latents, hparams):
"""Shape checking for cond_latents."""
if cond_latents is None:
return
if not isinstance(cond_latents[0], list):
cond_latents = [cond_latents]
exp_num_latents = hparams.num_cond_latents
if hparams.latent_dist_encoder == "conv_net":
exp_num_latents += ... |
def get_variable_ddi(name, shape, initial_value, dtype=tf.float32, init=False,
trainable=True):
"""Wrapper for data-dependent initialization."""
# If init is a tf bool: w is assigned dynamically at runtime.
# If init is a python bool: then w is determined during graph construction.
w = tf.g... |
def get_dropout(x, rate=0.0, init=True):
"""Dropout x with dropout_rate = rate.
Apply zero dropout during init or prediction time.
Args:
x: 4-D Tensor, shape=(NHWC).
rate: Dropout rate.
init: Initialization.
Returns:
x: activations after dropout.
"""
if init or rate == 0:
return x
re... |
def actnorm_3d(name, x, logscale_factor=3.):
"""Applies actnorm to each time-step independently.
There are a total of 2*n_channels*n_steps parameters learnt.
Args:
name: variable scope.
x: 5-D Tensor, (NTHWC)
logscale_factor: Increases the learning rate of the scale by
logscale_... |
def actnorm(name, x, logscale_factor=3., reverse=False, init=False,
trainable=True):
"""x_{ij} = s x x_{ij} + b. Per-channel scaling and bias.
If init is set to True, the scaling and bias are initialized such
that the mean and variance of the output activations of the first minibatch
are zero and o... |
def actnorm_center(name, x, reverse=False, init=False):
"""Add a bias to x.
Initialize such that the output of the first minibatch is zero centered
per channel.
Args:
name: scope
x: 2-D or 4-D Tensor.
reverse: Forward or backward operation.
init: data-dependent initialization.
Returns:
... |
def actnorm_scale(name, x, logscale_factor=3., reverse=False, init=False):
"""Per-channel scaling of x."""
x_shape = common_layers.shape_list(x)
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
# Variance initialization logic.
assert len(x_shape) == 2 or len(x_shape) == 4
if len(x_shape) == 2:
... |
def invertible_1x1_conv(name, x, reverse=False):
"""1X1 convolution on x.
The 1X1 convolution is parametrized as P*L*(U + sign(s)*exp(log(s))) where
1. P is a permutation matrix.
2. L is a lower triangular matrix with diagonal entries unity.
3. U is a upper triangular matrix where the diagonal entries zero.
... |
def add_edge_bias(x, filter_size):
"""Pad x and concatenates an edge bias across the depth of x.
The edge bias can be thought of as a binary feature which is unity when
the filter is being convolved over an edge and zero otherwise.
Args:
x: Input tensor, shape (NHWC)
filter_size: filter_size to determ... |
def time_pad(x, filter_size, dilations):
"""Pad left across time and pad valid across the spatial components.
Also concats a binary feature that indicates if a feature is padded or not.
Args:
x: 5-D Tensor, (NTHWC)
filter_size: list of ints
dilations: list of ints, dilations - 1 specifies the number... |
def conv(name, x, output_channels, filter_size=None, stride=None,
logscale_factor=3.0, apply_actnorm=True, conv_init="default",
dilations=None):
"""Convolutional layer with edge bias padding and optional actnorm.
If x is 5-dimensional, actnorm is applied independently across every
time-step.
... |
def conv_block(name, x, mid_channels, dilations=None, activation="relu",
dropout=0.0):
"""2 layer conv block used in the affine coupling layer.
Args:
name: variable scope.
x: 4-D or 5-D Tensor.
mid_channels: Output channels of the second layer.
dilations: Optional, list of integers.
... |
def dilated_conv_stack(name, x, mid_channels, output_channels,
dilation_rates, activation="relu",
dropout=0.0):
"""Dilated convolutional stack.
Features at different rates are computed independently using a 3 layer
convolutional stack and added.
Args:
name: va... |
def conv_stack(name, x, mid_channels, output_channels, dilations=None,
activation="relu", dropout=0.0):
"""3-layer convolutional stack.
Args:
name: variable scope.
x: 5-D Tensor.
mid_channels: Number of output channels of the first layer.
output_channels: Number of output channels.
... |
def additive_coupling(name, x, mid_channels=512, reverse=False,
activation="relu", dropout=0.0):
"""Reversible additive coupling layer.
Args:
name: variable scope.
x: 4-D Tensor, shape=(NHWC).
mid_channels: number of channels in the coupling layer.
reverse: Forward or reverse ... |
def affine_coupling(name, x, mid_channels=512, activation="relu",
reverse=False, dropout=0.0):
"""Reversible affine coupling layer.
Args:
name: variable scope.
x: 4-D Tensor.
mid_channels: number of channels in the coupling layer.
activation: Can be either "relu" or "gatu".
... |
def squeeze(name, x, factor=2, reverse=True):
"""Block-wise spatial squeezing of x to increase the number of channels.
Args:
name: Used for variable scoping.
x: 4-D Tensor of shape (batch_size X H X W X C)
factor: Factor by which the spatial dimensions should be squeezed.
reverse: Squueze or unsque... |
def get_dilation_rates(hparams, width):
"""Get a list of valid dilation rates.
Args:
hparams: HParams.
width: spatial dimension. Ensures that the effective filter size is
not larger than the spatial dimension.
Returns:
allowed_dilations: A list of dilation rates.
"""
# dil_rate=1 means... |
def temporal_latent_to_dist(name, x, hparams, output_channels=None):
"""Network that maps a time-indexed list of 3-D latents to a gaussian.
Args:
name: variable scope.
x: List of 4-D Tensors indexed by time, (NHWC)
hparams: tf.contrib.training.Hparams.
output_channels: int, Number of channels of th... |
def single_conv_dist(name, x, output_channels=None):
"""A 3x3 convolution mapping x to a standard normal distribution at init.
Args:
name: variable scope.
x: 4-D Tensor.
output_channels: number of channels of the mean and std.
"""
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_shape = com... |
def latent_to_dist(name, x, hparams, output_channels=None):
"""Map latent to the mean and log-scale of a Gaussian.
Args:
name: variable scope.
x: 4-D Tensor of shape (NHWC)
hparams: HParams.
latent_architecture - can be "single_conv", "glow_nn" or "glow_resnet",
defaul... |
def noise_op(latents, hparams):
"""Adds isotropic gaussian-noise to each latent.
Args:
latents: 4-D or 5-D tensor, shape=(NTHWC) or (NHWC).
hparams: HParams.
Returns:
latents: latents with isotropic gaussian noise appended.
"""
if hparams.latent_noise == 0 or hparams.mode != tf.estimator.ModeKeys... |
def merge_level_and_latent_dist(level_dist, latent_dist,
merge_std="prev_level"):
"""Merge level_dist and latent_dist.
new_dist ~ N(level_dist.mean + latent_dis.mean, std) where std is determined
according to merge_std.
Args:
level_dist: instance of tfp.distributions.Normal... |
def level_cond_prior(prior_dist, z, latent, hparams, state):
"""Returns a conditional prior for each level.
Args:
prior_dist: Distribution conditioned on the previous levels.
z: Tensor, output of the previous levels.
latent: Tensor or a list of tensors to condition the latent_distribution.
hparams:... |
def compute_prior(name, z, latent, hparams, condition=False, state=None,
temperature=1.0):
"""Distribution on z_t conditioned on z_{t-1} and latent.
Args:
name: variable scope.
z: 4-D Tensor.
latent: optional,
if hparams.latent_dist_encoder == "pointwise", this is a list
... |
def split(name, x, reverse=False, eps=None, eps_std=None, cond_latents=None,
hparams=None, state=None, condition=False, temperature=1.0):
"""Splits / concatenates x into x1 and x2 across number of channels.
For the forward pass, x2 is assumed be gaussian,
i.e P(x2 | x1) ~ N(mu, sigma) where mu and sigm... |
def revnet_step(name, x, hparams, reverse=True):
"""One step of glow generative flow.
Actnorm + invertible 1X1 conv + affine_coupling.
Args:
name: used for variable scope.
x: input
hparams: coupling_width is the only hparam that is being used in
this function.
reverse: forward or re... |
def revnet(name, x, hparams, reverse=True):
"""'hparams.depth' steps of generative flow.
Args:
name: variable scope for the revnet block.
x: 4-D Tensor, shape=(NHWC).
hparams: HParams.
reverse: bool, forward or backward pass.
Returns:
x: 4-D Tensor, shape=(NHWC).
objective: float.
"""
... |
def scale_gaussian_prior(name, z, logscale_factor=3.0, trainable=True):
"""Returns N(s^i * z^i, std^i) where s^i and std^i are pre-component.
s^i is a learnable parameter with identity initialization.
std^i is optionally learnable with identity initialization.
Args:
name: variable scope.
z: input_tens... |
def top_prior(name, z_shape, learn_prior="normal", temperature=1.0):
"""Unconditional prior distribution.
Args:
name: variable scope
z_shape: Shape of the mean / scale of the prior distribution.
learn_prior: Possible options are "normal" and "single_conv".
If set to "single_conv", the ... |
def uniform_binning_correction(x, n_bits=8):
"""Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0).
Args:
x: 4-D Tensor of shape (NHWC)
n_bits: optional.
Returns:
x: x ~ U(x, x + 1.0 / 256)
objective: Equivalent to -q(x)*log(q(x)).
"""
n_bins = 2**n_bits
batch_size, height, width, n_channels ... |
def encoder_decoder(name, x, hparams, eps=None, reverse=False,
cond_latents=None, condition=False, states=None,
temperature=1.0):
"""Glow encoder-decoder. n_levels of (Squeeze + Flow + Split.) operations.
Args:
name: variable scope.
x: 4-D Tensor, shape=(NHWC).
h... |
def bfloat16_activations_var_getter(getter, *args, **kwargs):
"""A custom getter function for float32 parameters and bfloat16 activations.
Args:
getter: custom getter
*args: arguments
**kwargs: keyword arguments
Returns:
variables with the correct dtype.
Raises:
KeyError: if "dtype" is not ... |
def float16_activations_var_getter(getter, *args, **kwargs):
"""A custom getter function for float32 parameters and float16 activations.
This function ensures the following:
1. All variables requested with type fp16 are stored as type fp32.
2. All variables requested with type fp32 are returned as type fp1... |
def simulated_quantize(x, num_bits, noise):
"""Simulate quantization to num_bits bits, with externally-stored scale.
num_bits is the number of bits used to store each value.
noise is a float32 Tensor containing values in [0, 1).
Each value in noise should take different values across
different steps, approxi... |
def noise_from_step_num():
"""Quantization noise equal to (phi * (step_num + 1)) mod 1.0.
Not using random_uniform here due to a problem on TPU in that random seeds
are not respected, which may cause the parameters on different replicas
to go out-of-sync.
Returns:
a float32 scalar
"""
step = tf.to_i... |
def _randomized_roundoff_to_bfloat16(x, noise, cand1, cand2):
"""Round-off x to cand1 or to cand2 in an unbiased way.
Cand1 and cand2 are the same shape as x.
For every element of x, the corresponding elements of cand1 and cand2 should
be the two closest bfloat16 values to x. Order does not matter.
cand1 an... |
def _to_bfloat16_unbiased(x, noise):
"""Convert a float32 to a bfloat16 using randomized roundoff.
Args:
x: A float32 Tensor.
noise: a float32 Tensor with values in [0, 1), broadcastable to tf.shape(x)
Returns:
A float32 Tensor.
"""
x_sign = tf.sign(x)
# Make sure x is positive. If it is zero,... |
def custom_getter(self, activation_dtype=tf.bfloat16):
"""A custom getter that uses the encoding for bfloat16 and float32 vars.
When a bfloat16 or float32 variable is requsted, an encoded float16
varaible is created, which is then decoded and cast to a bfloat16
activation.
Args:
activation_d... |
def load_videos(template, video_length, frame_shape):
"""Loads videos from files.
Args:
template: template string for listing the image files.
video_length: length of the video.
frame_shape: shape of each frame.
Returns:
dataset: the tf dataset frame by frame.
dataset_len: number of the item... |
def psnr_and_ssim(output, target):
"""Compute the PSNR and SSIM.
Args:
output: 4-D Tensor, shape=(num_frames, height, width, num_channels)
target: 4-D Tensor, shape=(num_frames, height, width, num_channels)
Returns:
psnr: 1-D Tensor, shape=(num_frames,)
ssim: 1-D Tensor, shape=(num_frames,)
"""... |
def get_zipped_dataset_from_predictions(predictions):
"""Creates dataset from in-memory predictions."""
targets = stack_data_given_key(predictions, "targets")
outputs = stack_data_given_key(predictions, "outputs")
num_videos, num_steps = targets.shape[:2]
# Truncate output time-steps to match target time-ste... |
def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos):
"""Computes the average of all the metric for one decoding.
Args:
iterator: dataset iterator.
feed_dict: feed dict to initialize iterator.
num_videos: number of videos.
Returns:
all_psnr: 2-D Numpy array, shape=(num_samples... |
def reduce_to_best_decode(metrics, reduce_func):
"""Extracts the best-decode from the metrics according to reduce_func.
Args:
metrics: 3-D numpy array, shape=(num_decodes, num_samples, num_frames)
reduce_func: callable, np.argmax or np.argmin.
Returns:
best_metrics: 2-D numpy array, shape=(num_sample... |
def compute_all_metrics_statistics(all_results):
"""Computes statistics of metrics across multiple decodings.
Args:
all_results: dict of 3-D numpy arrays.
Each array has shape=(num_decodes, num_samples, num_frames).
Returns:
statistics: dict of 1-D numpy arrays, shape=(num_frames).
... |
def compute_video_metrics_from_predictions(predictions, decode_hparams):
"""Computes metrics from predictions.
Args:
predictions: list of list of dicts.
outer length: num_decodes, inner_length: num_samples
decode_hparams: Decode hparams. instance of HParams.
Returns:
statistics: dict... |
def compute_video_metrics_from_png_files(
output_dirs, problem_name, video_length, frame_shape):
"""Computes the average of all the metric for one decoding.
This function assumes that all the predicted and target frames
have been saved on the disk and sorting them by name will result
to consecutive frames ... |
def compute_and_save_video_metrics(
output_dirs, problem_name, video_length, frame_shape):
"""Compute and saves the video metrics."""
statistics, all_results = compute_video_metrics_from_png_files(
output_dirs, problem_name, video_length, frame_shape)
for results, output_dir in zip(all_results, output_d... |
def swap_time_and_batch_axes(inputs):
"""Swaps time and batch axis (the first two axis)."""
transposed_axes = tf.concat([[1, 0], tf.range(2, tf.rank(inputs))], axis=0)
return tf.transpose(inputs, transposed_axes) |
def encode_to_shape(inputs, shape, scope):
"""Encode the given tensor to given image shape."""
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
w, h = shape[1], shape[2]
x = inputs
x = tfl.flatten(x)
x = tfl.dense(x, w * h, activation=None, name="enc_dense")
x = tf.reshape(x, (-1, w, h, 1))
... |
def decode_to_shape(inputs, shape, scope):
"""Encode the given tensor to given image shape."""
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = inputs
x = tfl.flatten(x)
x = tfl.dense(x, shape[2], activation=None, name="dec_dense")
x = tf.expand_dims(x, axis=1)
return x |
def basic_lstm(inputs, state, num_units, name=None):
"""Basic LSTM."""
input_shape = common_layers.shape_list(inputs)
# reuse parameters across time-steps.
cell = tf.nn.rnn_cell.BasicLSTMCell(
num_units, name=name, reuse=tf.AUTO_REUSE)
if state is None:
state = cell.zero_state(input_shape[0], tf.flo... |
def lstm_cell(inputs,
state,
num_units,
use_peepholes=False,
cell_clip=0.0,
initializer=None,
num_proj=None,
num_unit_shards=None,
num_proj_shards=None,
reuse=None,
name=None):
"... |
def conv_lstm_2d(inputs, state, output_channels,
kernel_size=5, name=None, spatial_dims=None):
"""2D Convolutional LSTM."""
input_shape = common_layers.shape_list(inputs)
batch_size, input_channels = input_shape[0], input_shape[-1]
if spatial_dims is None:
input_shape = input_shape[1:]
el... |
def scheduled_sample_count(ground_truth_x,
generated_x,
batch_size,
scheduled_sample_var):
"""Sample batch with specified mix of groundtruth and generated data points.
Args:
ground_truth_x: tensor of ground-truth data points.
... |
def inject_additional_input(layer, inputs, name, mode="concat"):
"""Injects the additional input into the layer.
Args:
layer: layer that the input should be injected to.
inputs: inputs to be injected.
name: TF scope name.
mode: how the infor should be added to the layer:
"concat" concats as a... |
def scheduled_sample_prob(ground_truth_x,
generated_x,
batch_size,
scheduled_sample_var):
"""Probability based scheduled sampling.
Args:
ground_truth_x: tensor of ground-truth data points.
generated_x: tensor of generated data po... |
def dna_transformation(prev_image, dna_input, dna_kernel_size, relu_shift):
"""Apply dynamic neural advection to previous image.
Args:
prev_image: previous image to be transformed.
dna_input: hidden lyaer to be used for computing DNA transformation.
dna_kernel_size: dna kernel size.
relu_shift: shi... |
def cdna_transformation(prev_image, cdna_input, num_masks, color_channels,
dna_kernel_size, relu_shift):
"""Apply convolutional dynamic neural advection to previous image.
Args:
prev_image: previous image to be transformed.
cdna_input: hidden lyaer to be used for computing CDNA kern... |
def vgg_layer(inputs,
nout,
kernel_size=3,
activation=tf.nn.leaky_relu,
padding="SAME",
is_training=True,
has_batchnorm=False,
scope=None):
"""A layer of VGG network with batch norm.
Args:
inputs: image tensor
... |
def tile_and_concat(image, latent, concat_latent=True):
"""Tile latent and concatenate to image across depth.
Args:
image: 4-D Tensor, (batch_size X height X width X channels)
latent: 2-D Tensor, (batch_size X latent_dims)
concat_latent: If set to False, the image is returned as is.
Returns:
con... |
def _encode_gif(images, fps):
"""Encodes numpy images into gif string.
Args:
images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape
`[time, height, width, channels]` where `channels` is 1 or 3.
fps: frames per second of the animation
Returns:
The encoded gif string.
Raises:
... |
def ffmpeg_works():
"""Tries to encode images with ffmpeg to check if it works."""
images = np.zeros((2, 32, 32, 3), dtype=np.uint8)
try:
_encode_gif(images, 2)
return True
except (IOError, OSError):
return False |
def py_gif_summary(tag, images, max_outputs, fps, return_summary_value=False):
"""Outputs a `Summary` protocol buffer with gif animations.
Args:
tag: Name of the summary.
images: A 5-D `uint8` `np.array` of shape `[batch_size, time, height, width,
channels]` where `channels` is 1 or 3.
max_output... |
def gif_summary(name, tensor, max_outputs=3, fps=10, collections=None,
family=None):
"""Outputs a `Summary` protocol buffer with gif animations.
Args:
name: Name of the summary.
tensor: A 5-D `uint8` `Tensor` of shape `[batch_size, time, height, width,
channels]` where `channels` is 1... |
def conv_latent_tower(images, time_axis, latent_channels=1, min_logvar=-5,
is_training=False, random_latent=False,
tiny_mode=False, small_mode=False):
"""Builds convolutional latent tower for stochastic model.
At training time this tower generates a latent distribution (... |
def beta_schedule(schedule, global_step, final_beta, decay_start, decay_end):
"""Get KL multiplier (beta) based on the schedule."""
if decay_start > decay_end:
raise ValueError("decay_end is smaller than decay_end.")
# Since some of the TF schedules do not support incrementing a value,
# in all of the sche... |
def extract_random_video_patch(videos, num_frames=-1):
"""For every video, extract a random consecutive patch of num_frames.
Args:
videos: 5-D Tensor, (NTHWC)
num_frames: Integer, if -1 then the entire video is returned.
Returns:
video_patch: 5-D Tensor, (NTHWC) with T = num_frames.
Raises:
Val... |
def write_multi(self, frames, encoded_frames=None):
"""Writes multiple video frames."""
if encoded_frames is None:
# Infinite iterator.
encoded_frames = iter(lambda: None, 1)
for (frame, encoded_frame) in zip(frames, encoded_frames):
self.write(frame, encoded_frame) |
def __init_ffmpeg(self, image_shape):
"""Initializes ffmpeg to write frames."""
import itertools # pylint: disable=g-import-not-at-top
from subprocess import Popen, PIPE # pylint: disable=g-import-not-at-top,g-multiple-import,g-importing-member
ffmpeg = "ffmpeg"
height, width, channels = image_sha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.