INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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...
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...
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...
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 ...
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 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...
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] for cond_latent in cond_latents] elif hparams.latent_dist_encod...
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 == "conv_net": exp_num_latents += ...
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 determined during graph construction. w = tf.g...
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 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...
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...
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_...
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_...
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...
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.
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: ...
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 if len(x_shape) == 2: ...
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...
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. ...
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...
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...
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...
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...
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...
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. ...
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 ...
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. ...
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...
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...
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...
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. ...
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...
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 ...
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...
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". ...
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...
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...
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 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...
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 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...
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. 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...
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-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...
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...
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...
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...
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:...
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 ...
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 ...
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). ...
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...
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...
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...
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): """'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. """ ...
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...
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...
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 ...
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 ...
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: 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 ...
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....
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...
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, *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 ...
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-...
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...
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...
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...
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 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...
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...
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...
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: 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,...
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...
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...
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...
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...
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): """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,) """...
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] # Truncate output time-steps to match target time-ste...
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)
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...
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, ...
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...
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...
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). ...
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 ...
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...
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...
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 ...
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, output_dir in zip(all_results, output_d...
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_dense") x = tf.reshape(x, (-1, w, h, 1)) ...
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_dims(x, axis=1) return x
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_shape[0], tf.flo...
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, name=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_shape = input_shape[1:] el...
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 ...
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. ...
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...
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...
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 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...
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 ...
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...
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 ...
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...
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...
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 ...
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...
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...
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...
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: ...
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 ...
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...
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...
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...
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...
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 (...
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 support incrementing a value, # in all of the sche...
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...
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...
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_frame)
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" height, width, channels = image_sha...
Starts a thread for reading output from FFMPEG. The thread reads consecutive chunks from the stream and saves them in the given list. Args: stream: output stream of the FFMPEG process. chunks: list to save output chunks to. Returns: Thread
def _start_reader_thread(self, stream, chunks): """Starts a thread for reading output from FFMPEG. The thread reads consecutive chunks from the stream and saves them in the given list. Args: stream: output stream of the FFMPEG process. chunks: list to save output chunks to. Returns: ...
Finishes transconding and returns the video. Returns: bytes Raises: IOError: in case of transcoding error.
def finish(self): """Finishes transconding and returns the video. Returns: bytes Raises: IOError: in case of transcoding error. """ if self.proc is None: return None self.proc.stdin.close() for thread in (self._out_thread, self._err_thread): thread.join() (out, ...
Validates flags are set to acceptable values.
def validate_flags(): """Validates flags are set to acceptable values.""" if FLAGS.cloud_mlengine_model_name: assert not FLAGS.server assert not FLAGS.servable_name else: assert FLAGS.server assert FLAGS.servable_name
Returns a request function.
def make_request_fn(): """Returns a request function.""" if FLAGS.cloud_mlengine_model_name: request_fn = serving_utils.make_cloud_mlengine_request_fn( credentials=GoogleCredentials.get_application_default(), model_name=FLAGS.cloud_mlengine_model_name, version=FLAGS.cloud_mlengine_model_...
Convnet that encodes inputs into mean and std of a gaussian. Args: inputs: 5-D Tensor, shape (batch_size, num_frames, width, height, channels) n_layers: Number of layers. Returns: z_mu: Mean of the latent gaussians. z_log_var: log(var) of the latent gaussians. Raises: ValueError...
def encoder(self, inputs, n_layers=3): """Convnet that encodes inputs into mean and std of a gaussian. Args: inputs: 5-D Tensor, shape (batch_size, num_frames, width, height, channels) n_layers: Number of layers. Returns: z_mu: Mean of the latent gaussians. z_log_var: log(var) of the l...
Get expected fully connected shape after a series of convolutions.
def get_fc_dimensions(self, strides, kernel_sizes): """Get expected fully connected shape after a series of convolutions.""" output_height, output_width, _ = self.hparams.problem.frame_shape output_steps = self.hparams.video_num_target_frames output_shape = np.array([output_steps, output_height, output_...
3-D SNGAN discriminator. Args: frames: a list of batch-major tensors indexed by time. Returns: logits: 1-D Tensor with shape=batch_size. Positive logits imply that the discriminator thinks that it belongs to the true class.
def discriminator(self, frames): """3-D SNGAN discriminator. Args: frames: a list of batch-major tensors indexed by time. Returns: logits: 1-D Tensor with shape=batch_size. Positive logits imply that the discriminator thinks that it belongs to the true class. ""...
Performs the discriminator step in computing the GAN loss. Applies stop-gradient to the generated frames while computing the discriminator loss to make sure that the gradients are not back-propagated to the generator. This makes sure that only the discriminator is updated. Args: true_frames: Tru...
def d_step(self, true_frames, gen_frames): """Performs the discriminator step in computing the GAN loss. Applies stop-gradient to the generated frames while computing the discriminator loss to make sure that the gradients are not back-propagated to the generator. This makes sure that only the discrimin...
Performs the generator step in computing the GAN loss. Args: gen_frames: Generated frames fake_logits_stop: Logits corresponding to the generated frames as per the discriminator. Assumed to have a stop-gradient term. Returns: gan_g_loss_pos_d: Loss. gan_g_loss_ne...
def g_step(self, gen_frames, fake_logits_stop): """Performs the generator step in computing the GAN loss. Args: gen_frames: Generated frames fake_logits_stop: Logits corresponding to the generated frames as per the discriminator. Assumed to have a stop-gradient term. Ret...
Get the discriminator + generator loss at every step. This performs an 1:1 update of the discriminator and generator at every step. Args: true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C) Assumed to be ground truth. gen_frames: 5-D Tensor of shape (num_steps,...
def get_gan_loss(self, true_frames, gen_frames, name): """Get the discriminator + generator loss at every step. This performs an 1:1 update of the discriminator and generator at every step. Args: true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C) Assumed to be g...
Gets extra loss from VAE and GAN.
def get_extra_loss(self, latent_means=None, latent_stds=None, true_frames=None, gen_frames=None): """Gets extra loss from VAE and GAN.""" if not self.is_training: return 0.0 vae_loss, d_vae_loss, d_gan_loss = 0.0, 0.0, 0.0 # Use sv2p's KL divergence computation. if self.h...
Pad, apply 3-D convolution and leaky relu.
def pad_conv3d_lrelu(self, activations, n_filters, kernel_size, strides, scope): """Pad, apply 3-D convolution and leaky relu.""" padding = [[0, 0], [1, 1], [1, 1], [1, 1], [0, 0]] # tf.nn.conv3d accepts a list of 5 values for strides # with first and last value equal to 1 if...
Weight-level magnitude pruning.
def weight(w, sparsity): """Weight-level magnitude pruning.""" w_shape = common_layers.shape_list(w) k = int(np.prod(w_shape[:-1])) count = tf.to_int32(k * sparsity) mask = common_layers.weight_targeting(w, count) return (1 - mask) * w
Unit-level magnitude pruning.
def unit(w, sparsity): """Unit-level magnitude pruning.""" w_shape = common_layers.shape_list(w) count = tf.to_int32(w_shape[-1] * sparsity) mask = common_layers.unit_targeting(w, count) return (1 - mask) * w
Prune the weights of a model and evaluate.
def sparsify(sess, eval_model, pruning_strategy, pruning_params): """Prune the weights of a model and evaluate.""" weights = tf.trainable_variables() def should_prune(name): """Whether to prune a weight or not.""" in_whitelist = not pruning_params.white_list or any( e in name for e in pruning_par...
Loads the configuration.
def load_config(self): """Loads the configuration.""" config = dict([(key, value) for key, value in iteritems(self.options) if key in self.cfg.settings and value is not None]) for key, value in iteritems(config): self.cfg.set(key.lower(), value)
Set of hyperparameters.
def ppo_base_v1(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.learning_rate_schedule = "constant" hparams.learning_rate_constant = 1e-4 hparams.clip_grad_norm = 0.5 hparams.weight_decay = 0 # If set, extends the LR warmup to all epochs except the final one. hparams.ad...
Pong base parameters.
def ppo_atari_base(): """Pong base parameters.""" hparams = ppo_discrete_action_base() hparams.learning_rate_constant = 1e-4 hparams.epoch_length = 200 hparams.gae_gamma = 0.985 hparams.gae_lambda = 0.985 hparams.entropy_loss_coef = 0.003 hparams.value_loss_coef = 1 hparams.optimization_epochs = 3 h...
Parameters based on the original PPO paper.
def ppo_original_params(): """Parameters based on the original PPO paper.""" hparams = ppo_atari_base() hparams.learning_rate_constant = 2.5e-4 hparams.gae_gamma = 0.99 hparams.gae_lambda = 0.95 hparams.clipping_coef = 0.1 hparams.value_loss_coef = 1 hparams.entropy_loss_coef = 0.01 hparams.eval_every...
Atari parameters with world model as policy.
def ppo_original_world_model(): """Atari parameters with world model as policy.""" hparams = ppo_original_params() hparams.policy_network = "next_frame_basic_deterministic" hparams_keys = hparams.values().keys() video_hparams = basic_deterministic_params.next_frame_basic_deterministic() for (name, value) in...
Atari parameters with world model as policy.
def ppo_tiny_world_model(): """Atari parameters with world model as policy.""" hparams = ppo_original_params() hparams.policy_network = "next_frame_basic_deterministic" hparams_keys = hparams.values().keys() video_hparams = basic_deterministic_params.next_frame_tiny() for (name, value) in six.iteritems(vide...
Atari parameters with stochastic discrete world model as policy.
def ppo_original_world_model_stochastic_discrete(): """Atari parameters with stochastic discrete world model as policy.""" hparams = ppo_original_params() hparams.policy_network = "next_frame_basic_stochastic_discrete" hparams_keys = hparams.values().keys() video_hparams = basic_stochastic.next_frame_basic_st...
Returns a function creating a simulated env, in or out of graph. Args: **env_kwargs: kwargs to pass to the simulated env constructor. Returns: Function in_graph -> env.
def make_simulated_env_fn(**env_kwargs): """Returns a function creating a simulated env, in or out of graph. Args: **env_kwargs: kwargs to pass to the simulated env constructor. Returns: Function in_graph -> env. """ def env_fn(in_graph): class_ = SimulatedBatchEnv if in_graph else SimulatedBatc...
Extracts simulated env kwargs from real_env and loop hparams.
def make_simulated_env_kwargs(real_env, hparams, **extra_kwargs): """Extracts simulated env kwargs from real_env and loop hparams.""" objs_and_attrs = [ (real_env, [ "reward_range", "observation_space", "action_space", "frame_height", "frame_width" ]), (hparams, ["frame_stack_s...
Get a policy network. Args: observations: observations hparams: parameters action_space: action space Returns: Tuple (action logits, value).
def get_policy(observations, hparams, action_space): """Get a policy network. Args: observations: observations hparams: parameters action_space: action space Returns: Tuple (action logits, value). """ if not isinstance(action_space, gym.spaces.Discrete): raise ValueError("Expecting discr...
Base set of hparams for model-free PPO.
def rlmf_tictactoe(): """Base set of hparams for model-free PPO.""" hparams = rlmf_original() hparams.game = "tictactoe" hparams.rl_env_name = "T2TEnv-TicTacToeEnv-v0" # Since we don't have any no-op actions, otherwise we have to have an # attribute called `get_action_meanings`. hparams.eval_max_num_noops...
Tiny set of hparams for model-free PPO.
def rlmf_tiny(): """Tiny set of hparams for model-free PPO.""" hparams = rlmf_original() hparams = hparams.override_from_dict(rlmf_tiny_overrides()) hparams.batch_size = 2 hparams.base_algo_params = "ppo_original_tiny" hparams.add_hparam("ppo_epochs_num", 3) hparams.add_hparam("ppo_epoch_length", 2) ret...