text
stringlengths
81
112k
Extract the title from a page. Args: page: a unicode string Returns: a unicode string def _page_to_title(page): """Extract the title from a page. Args: page: a unicode string Returns: a unicode string """ # print("page=%s" % page) start_tag = u"<title>" end_tag = u"</title>" start...
Extract the text from a page. Args: page: a unicode string Returns: a unicode string def _page_to_text(page): """Extract the text from a page. Args: page: a unicode string Returns: a unicode string """ # text start tag looks like "<text ..otherstuff>" start_pos = page.find(u"<text") ...
Remove everything found between instances of start_string and end_string. Replace each such instance with replace_fn(removed_text) e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x) = u"the fat cat sat" Args: text: a unicode string start_string: a unicode string end_s...
Remove double brackets (internal links) but leave the viewable text. Args: text: a unicode string Returns: a unicode string def _remove_double_brackets(text): """Remove double brackets (internal links) but leave the viewable text. Args: text: a unicode string Returns: a unicode string """...
A stack of self attention layers. def image_encoder(image_feat, hparams, name="image_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = image_feat image_hidden_size = hparams.image_hidden_s...
Prepare question encoder. Args: inputs: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor, bottom of encoder stack encoder_self_attention_bias: a bias tensor for use in encoder self-attention def prepare_question_encoder(inputs, hparams): """Prepare question encoder. Ar...
A stack of self attention layers. def question_encoder(question, question_self_attention_bias, hparams, name="question_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers...
Attention on image feature with question as query. def attn(image_feat, query, hparams, name="attn", save_weights_to=None, make_image_summary=True): """Attention on image feature with question as query.""" with tf.variable_scope(name, "attn", values=[image_feat, query])...
Multi layer perceptron with dropout and relu activation. def mlp(feature, hparams, name="mlp"): """Multi layer perceptron with dropout and relu activation.""" with tf.variable_scope(name, "mlp", values=[feature]): num_mlp_layers = hparams.num_mlp_layers mlp_size = hparams.mlp_size for _ in range(num_ml...
Prepare encoder. Args: image_feat: a Tensor. question: a Tensor. hparams: run hyperparameters Returns: encoder_input: a Tensor, bottom of encoder stack encoder_self_attention_bias: a bias tensor for use in encoder self-attention def prepare_image_question_encoder(image_feat, question, hparams...
A stack of self attention layers. def image_question_encoder(encoder_inputs, encoder_self_attention_bias, hparams, query=None, name="image_question_encoder", save_weights_to=None, ...
A stack of transformer layers. Args: decoder_input: a Tensor encoder_output: a Tensor decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()) encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention (see common_attention.attenti...
Iterative encoder decoder. def iterative_encoder_decoder(encoder_input, encoder_self_attention_bias, encoder_decoder_attention_bias, query, hparams): """Iterative encoder decoder.""" for _ in ran...
VQA attention baseline hparams. def vqa_self_attention_base(): """VQA attention baseline hparams.""" hparams = common_hparams.basic_params1() hparams.batch_size = 128 hparams.use_fixed_batch_size = True, hparams.optimizer = "adam" hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.997 ...
Big model. def vqa_self_attention_feature_batch1024_big(): """Big model.""" hparams = vqa_self_attention_feature_batch1024() hparams.learning_rate_constant = 7e-4 hparams.batch_size = 256 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.num_heads = 16 hparams.layer_prepostprocess_dropout =...
A default set of length-bucket boundaries. def _bucket_boundaries(max_length, min_length=8, length_bucket_step=1.1): """A default set of length-bucket boundaries.""" assert length_bucket_step > 1.0 x = min_length boundaries = [] while x < max_length: boundaries.append(x) x = max(x + 1, int(x * length...
A batching scheme based on model hyperparameters. Every batch contains a number of sequences divisible by `shard_multiplier`. Args: batch_size: int, total number of tokens in a batch. max_length: int, sequences longer than this will be skipped. Defaults to batch_size. min_length_bucket: int ...
Wrapper around _batching_scheme with hparams. def hparams_to_batching_scheme(hparams, drop_long_sequences=False, shard_multiplier=1, length_multiplier=1): """Wrapper around _batching_scheme with hparams.""" return batching...
Pads unknown features' dimensions for TPU. def pad_for_tpu(shapes_dict, hparams, max_length): """Pads unknown features' dimensions for TPU.""" padded_shapes = {} def get_filler(specified_max_length): if not specified_max_length: return max_length return min(specified_max_length, max_length) inp...
Set the right shapes for the features. def standardize_shapes(features, batch_size=None): """Set the right shapes for the features.""" for fname in ["inputs", "targets"]: if fname not in features: continue f = features[fname] while len(f.get_shape()) < 4: f = tf.expand_dims(f, axis=-1) ...
Return the number of TFRecords in a file. def _file_num_records_cached(filename): """Return the number of TFRecords in a file.""" # Cache the result, as this is expensive to compute if filename in _file_num_records_cache: return _file_num_records_cache[filename] ret = 0 for _ in tf.python_io.tf_record_it...
Pad batch dim of features to nearest multiple of batch_multiple. def pad_batch(features, batch_multiple): """Pad batch dim of features to nearest multiple of batch_multiple.""" feature = list(features.items())[0][1] batch_size = tf.shape(feature)[0] mod = batch_size % batch_multiple has_mod = tf.cast(tf.cast...
Builds input pipeline for problem. Args: dataset: the dataset to make input function from. filepattern: the pattern of files to read from. skip_random_fraction_when_training: whether to skip randomly when training. batch_size_means_tokens_param: whether batch size should mean tokens. batch_size_m...
Generate start and end indices per outfile. def generate_shard_args(outfiles, num_examples): """Generate start and end indices per outfile.""" num_shards = len(outfiles) num_examples_per_shard = num_examples // num_shards start_idxs = [i * num_examples_per_shard for i in range(num_shards)] end_idxs = list(st...
Generate example dicts. def dataset_generator(filepath, dataset, chunk_size=1, start_idx=None, end_idx=None): """Generate example dicts.""" encoder = dna_encoder.DNAEncoder(chunk_size=chunk_size) with h5py.File(filepath, "r")...
Convert single h5 record to an example dict. def to_example_dict(encoder, inputs, mask, outputs): """Convert single h5 record to an example dict.""" # Inputs bases = [] input_ids = [] last_idx = -1 for row in np.argwhere(inputs): idx, base_id = row idx, base_id = int(idx), int(base_id) assert i...
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 interpolations at coeffs[i]. shape=(l...
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 floats. rank: integer. Returns: interp_latents: list of in...
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 representing images or videos. def postproce...
Returns a single or list of conditional latents at level 'level'. 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] ...
Shape checking for cond_latents. 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 == "...
Wrapper for data-dependent initialization. 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 dete...
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. def get_dropout(x, rate=0.0, init=True): """Dropout x with dropout_rate = rate. Apply z...
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_factor. Returns: x: 5-D Tensor, (NTHWC) with...
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 one respectively. Args: name: variable scope. x: input logscale_factor: Used in actnorm_...
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: x_center: (x + b), if reverse is True and (x - b) otherwise. ...
Per-channel scaling of x. 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 ...
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. 4. s is a vector. sign(s) and P are fixed and the...
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 determine padding. Returns: x_pad: Input...
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 of holes between two filter el...
Convolutional layer with edge bias padding and optional actnorm. If x is 5-dimensional, actnorm is applied independently across every time-step. Args: name: variable scope. x: 4-D Tensor or 5-D Tensor of shape NHWC or NTHWC output_channels: Number of output channels. filter_size: list of ints, i...
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. activation: relu or gatu. If relu, the second layer is relu(W*x) If gatu, the second layer ...
Dilated convolutional stack. Features at different rates are computed independently using a 3 layer convolutional stack and added. Args: name: variable scope. x: 5-D Tensor. mid_channels: Number of output channels of the first layer in the conv stack. output_channels: Number of...
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. dilations: Dilations to apply in the first 3x3 layer and the last 3x3 layer. By default, apply no dilation...
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 operation. activation: "relu" or "gatu" dropout: default, 0.0 Returns: output: 4-D Tensor, shape=(NHWC) ob...
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". reverse: Forward or reverse operation. dropout: default, 0.0 Returns: output: x shifted and scaled by an affin...
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 unsqueeze operation. Returns: x: 4-D Tensor of sha...
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. def get_dilation_rates(hparams, width): """Get a list of valid dilat...
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 the output gaussian mean. Returns: dist: tfp.distributions.Normal def...
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. def single_conv_dist(name, x, output_channels=None): """A 3x3 convolution mapping x to a standard normal distribution at init. A...
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", default = single_conv latent_encoder_depth - int, depth of archit...
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. def noise_op(latents, hparams): """Adds isotropic gaussian-noise to each latent. Args: latents: 4-D or 5...
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 latent_dist: instance of tfp.distributions.Normal merge_std: can be "prev_level", "prev_step" or "normal". R...
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: next_frame_glow hparams. state: Current LSTM state. Used only...
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 of 4-D Tensors of length hparams.num_cond_latents. else, this is just a 4-D Tensor ...
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 sigma are the outputs of a network conditioned on x1 and optionally on cond_latents. For the reverse pass, x2 is determined from mu(x1) and sigma(x1). ...
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 reverse pass. Returns: z: Output of one step of re...
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 revnet(name, x, hparams, reverse=True): """'hparam...
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_tensor logscale_factor: equivalent to scaling up the learning_rate by a facto...
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 gaussian is parametrized by a single convolutional layer ...
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)). def uniform_binning_correction(x, n_bits=8): """Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0). Args: x: ...
Glow encoder-decoder. n_levels of (Squeeze + Flow + Split.) operations. Args: name: variable scope. x: 4-D Tensor, shape=(NHWC). hparams: HParams. eps: Stores (glow(x) - mu) / sigma during the forward pass. Used only to test if the network is reversible. reverse: Forward or reverse pass....
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 provided as a kwarg. def bfloat16_activations_var_getter(getter, *...
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 fp16. See https://docs.nvidia.com/deeplearning/sdk/mixed-precision-...
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, approximating a uniform distribution over [0, 1). In t...
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 def noise_from_step_num(): """Quantization noise eq...
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 and cand2 must differ from each other. Args: x: A float32 Tens...
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. def _to_bfloat16_unbiased(x, noise): """Convert a float32 to a bfloat16 using randomized roundoff. Args: ...
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_dtype: a dtype to which to convert the decoded value. Retu...
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 items which is the number of image files. Raises: ValueE...
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 psnr_and_ssim(output, target): """Comp...
Creates dataset from in-memory predictions. 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] # Trunca...
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, num_frames) all_ssim: 2-D Numpy array, shape=(num_samples, num_frames) ...
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_samples, num_frames). best_decode_ind: 1-D numpy array, ...
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). First the statistic (max/mean/std) is compu...
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 of Tensors, key being the metric with each Tensor having the ...
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 saved in order. Args: output_dirs: directory with all the saved frames. problem_name: prefix of...
Compute and saves the video metrics. 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, o...
Swaps time and batch axis (the first two axis). 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)
Encode the given tensor to given image shape. 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...
Encode the given tensor to given image shape. 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_...
Basic LSTM. 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_sha...
Full LSTM cell. 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, ...
2D Convolutional LSTM. 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_shap...
Sample batch with specified mix of groundtruth and generated data points. Args: ground_truth_x: tensor of ground-truth data points. generated_x: tensor of generated data points. batch_size: batch size scheduled_sample_var: number of ground-truth examples to include in batch. Returns: New batch ...
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 additional channels. "multiplicative" broadcasts inputs and multi...
Probability based scheduled sampling. Args: ground_truth_x: tensor of ground-truth data points. generated_x: tensor of generated data points. batch_size: batch size scheduled_sample_var: probability of choosing from ground_truth. Returns: New batch with randomly selected data points. def sched...
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: shift for ReLU function. Returns: List of images transformed by the predicted ...
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 kernels. num_masks: number of masks and hence the number of CDNA transformations. color_channels: the number of color channels in ...
A layer of VGG network with batch norm. Args: inputs: image tensor nout: number of output channels kernel_size: size of the kernel activation: activation function padding: padding of the image is_training: whether it is training mode or not has_batchnorm: whether batchnorm is applied or n...
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: concat_latent: 4-D Tensor, (batch_size X height X width X channe...
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: IOError: If the ffmpeg command ret...
Tries to encode images with ffmpeg to check if it works. 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
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_outputs: Max number of batch elements to generate gifs for. fps: frames per second of ...
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 or 3. max_outputs: Max number of batch elements to generate gifs for. fps: frames per second of t...
Builds convolutional latent tower for stochastic model. At training time this tower generates a latent distribution (mean and std) conditioned on the entire video. This latent variable will be fed to the main tower as an extra variable to be used for future frames prediction. At inference time, the tower is di...
Get KL multiplier (beta) based on the schedule. 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 sup...
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: ValueError: If num_frames is greater than the number of total f...
Writes multiple video frames. 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...
Initializes ffmpeg to write frames. 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" ...