text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 pe... |
_, height, width, channels = common_layers.shape_list(x)
w_shape = [channels, channels]
# Random rotation-matrix Q
random_matrix = np.random.rand(channels, channels)
np_w = scipy.linalg.qr(random_matrix)[0].astype("float32")
# Initialize P,L,U and s from the LU decomposition of a random rotation matrix
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 uni... |
x_shape = common_layers.shape_list(x)
if filter_size[0] == 1 and filter_size[1] == 1:
return x
a = (filter_size[0] - 1) // 2 # vertical padding size
b = (filter_size[1] - 1) // 2 # horizontal padding size
padding = [[0, 0], [a, a], [b, b], [0, 0]]
x_bias = tf.zeros(x_shape[:-1] + [1])
x = tf.pad(x... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 f... |
x_shape = common_layers.shape_list(x)
if filter_size == [1, 1, 1]:
return x
_, h, w = filter_size
eff_h = h + (h - 1)*(dilations[2] - 1)
eff_w = w + (w - 1)*(dilations[3] - 1)
a = (eff_h - 1) // 2 # vertical padding size
b = (eff_w - 1) // 2 # horizontal padding size
c = filter_size[0] - 1
# p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conv(name, x, output_channels, filter_size=None, stride=None, logscale_factor=3.0, apply_actnorm=True, conv_init="default", dilations=None):
"""Convolutional... |
if conv_init == "zeros" and apply_actnorm:
raise ValueError("apply_actnorm is unstable when init is set to zeros.")
x_shape = common_layers.shape_list(x)
is_2d = len(x_shape) == 4
num_steps = x_shape[1]
# set filter_size, stride and in_channels
if is_2d:
if filter_size is None:
filter_size ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: varia... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_shape = common_layers.shape_list(x)
is_2d = len(x_shape) == 4
num_steps = x_shape[1]
if is_2d:
first_filter = [3, 3]
second_filter = [1, 1]
else:
# special case when number of steps equal 1 to avoid
# padding.
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dilated_conv_stack(name, x, mid_channels, output_channels, dilation_rates, activation="relu", dropout=0.0):
"""Dilated convolutional stack. Features at diffe... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
output = 0.0
for dil_ind, dil_rate in enumerate(dilation_rates):
# TODO(mechcoder) try (concat across channels + 1x1) modulo memory issues.
curr_out = conv_stack("dil_%d" % dil_ind, x, mid_channels=mid_channels,
output... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conv_stack(name, x, mid_channels, output_channels, dilations=None, activation="relu", dropout=0.0):
"""3-layer convolutional stack. Args: name: variable scop... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x = conv_block("conv_block", x, mid_channels=mid_channels,
dilations=dilations, activation=activation,
dropout=dropout)
# Final layer.
x = conv("zeros", x, apply_actnorm=False, conv_init="zeros",
outpu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def additive_coupling(name, x, mid_channels=512, reverse=False, activation="relu", dropout=0.0):
"""Reversible additive coupling layer. Args: name: variable scop... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
output_channels = common_layers.shape_list(x)[-1] // 2
x1, x2 = tf.split(x, num_or_size_splits=2, axis=-1)
z1 = x1
shift = conv_stack("nn", x1, mid_channels, output_channels=output_channels,
activation=activation, dropout=drop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def affine_coupling(name, x, mid_channels=512, activation="relu", reverse=False, dropout=0.0):
"""Reversible affine coupling layer. Args: name: variable scope. x... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_shape = common_layers.shape_list(x)
x1, x2 = tf.split(x, num_or_size_splits=2, axis=-1)
# scale, shift = NN(x1)
# If reverse:
# z2 = scale * (x2 + shift)
# Else:
# z2 = (x2 / scale) - shift
z1 = x1
log_scale_and_shift = conv_st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: ... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
shape = common_layers.shape_list(x)
if factor == 1:
return x
height = int(shape[1])
width = int(shape[2])
n_channels = int(shape[3])
if not reverse:
assert height % factor == 0 and width % factor == 0
x = tf.reshape(x, [-1,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dilation_rates(hparams, width):
"""Get a list of valid dilation rates. Args: hparams: HParams. width: spatial dimension. Ensures that the effective filte... |
# dil_rate=1 means no dilation.
allowed_dilations = [[1]*5]
apply_dilations = hparams.get("latent_apply_dilations", False)
dilation_rates = hparams.get("latent_dilation_rates", [1, 3])
if apply_dilations:
for rate in dilation_rates:
# k + (k - 1) * rate but k is harcoded to be 3 everywhere.
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
_, _, width, _, res_channels = common_layers.shape_list(x)
if output_channels is None:
output_channels = res_channels
dilation_rates = get_dilation_rates(hparams, width)
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
h = x
for i in range(hparams.latent_encoder_depth):
if hparams.latent_ap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_shape = common_layers.shape_list(x)
if output_channels is None:
output_channels = x_shape[-1]
mean_log_scale = conv("conv2d", x, output_channels=2*output_channels,
conv_init="zeros", apply_actnorm=False)
mean = mean_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 s... |
architecture = hparams.get("latent_architecture", "single_conv")
depth = hparams.get("latent_encoder_depth", 1)
pre_output_channels = hparams.get("latent_pre_output_channels", 512)
width = hparams.get("latent_encoder_width", 512)
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
x_shape = common_layers... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Ret... |
if hparams.latent_noise == 0 or hparams.mode != tf.estimator.ModeKeys.TRAIN:
return latents
latent_shape = common_layers.shape_list(latents)
return latents + tf.random_normal(latent_shape, stddev=hparams.latent_noise) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.... |
level_mean, level_std = level_dist.loc, level_dist.scale
latent_mean, latent_std = latent_dist.loc, latent_dist.scale
new_mean = level_mean + latent_mean
if merge_std == "normal":
z_shape = common_layers.shape_list(latent_mean)
log_scale = tf.get_variable(
"merge_std", shape=z_shape, dtype=tf.f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def level_cond_prior(prior_dist, z, latent, hparams, state):
"""Returns a conditional prior for each level. Args: prior_dist: Distribution conditioned on the pre... |
latent_dist_encoder = hparams.get("latent_dist_encoder", None)
latent_skip = hparams.get("latent_skip", False)
if latent_dist_encoder == "pointwise":
last_latent = latent
merge_std = hparams.level_scale
latent_shape = common_layers.shape_list(latent)
z_shape = common_layers.shape_list(z)
if l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revnet_step(name, x, hparams, reverse=True):
"""One step of glow generative flow. Actnorm + invertible 1X1 conv + affine_coupling. Args: name: used for varia... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
if hparams.coupling == "additive":
coupling_layer = functools.partial(
additive_coupling, name="additive", reverse=reverse,
mid_channels=hparams.coupling_width,
activation=hparams.activation, dropout=hparams.coupling_dropout)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=(N... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
steps = np.arange(hparams.depth)
if reverse:
steps = steps[::-1]
objective = 0.0
for step in steps:
x, curr_obj = revnet_step(
"revnet_step_%d" % step, x, hparams, reverse=reverse)
objective += curr_obj
return x, obje... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 /... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
h = tf.zeros(z_shape, dtype=tf.float32)
if learn_prior == "normal":
prior_dist = tfp.distributions.Normal(h, tf.exp(h))
elif learn_prior == "single_conv":
prior_dist = single_conv_dist("top_learn_prior", h)
else:
raise ValueError("E... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bfloat16_activations_var_getter(getter, *args, **kwargs):
"""A custom getter function for float32 parameters and bfloat16 activations. Args: getter: custom g... |
requested_dtype = kwargs["dtype"]
if requested_dtype == tf.bfloat16:
kwargs["dtype"] = tf.float32
var = getter(*args, **kwargs)
# This if statement is needed to guard the cast, because batch norm
# assigns directly to the return value of this custom getter. The cast
# makes the return value not a varia... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def float16_activations_var_getter(getter, *args, **kwargs):
"""A custom getter function for float32 parameters and float16 activations. This function ensures th... |
requested_dtype = kwargs["dtype"]
if requested_dtype == tf.float16:
kwargs["dtype"] = tf.float32
if requested_dtype == tf.float32:
requested_dtype = tf.float16
var = getter(*args, **kwargs)
# This if statement is needed to guard the cast, because batch norm
# assigns directly to the return value ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
shape = x.get_shape().as_list()
if not (len(shape) >= 2 and shape[-1] > 1):
return x
max_abs = tf.reduce_max(tf.abs(x), -1, keepdims=True) + 1e-9
max_int = 2 ** (num_bits - 1) - 1
scale = max_abs / max_int
x /= scale
x = tf.floor(x + noise)
# dequantize before storing (since this is a simulation)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Fo... |
cand1_f = tf.to_float(cand1)
cand2_f = tf.to_float(cand2)
step_size = cand2_f - cand1_f
fpart = (x - cand1_f) / step_size
ret = tf.where(tf.greater(fpart, noise), cand2, cand1)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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... |
x_sign = tf.sign(x)
# Make sure x is positive. If it is zero, the two candidates are identical.
x = x * x_sign + 1e-30
cand1 = tf.to_bfloat16(x)
cand1_f = tf.to_float(cand1)
# This relies on the fact that for a positive bfloat16 b,
# b * 1.005 gives you the next higher bfloat16 and b*0.995 gives you the... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 variab... |
def getter_fn(getter, *args, **kwargs):
requested_dtype = kwargs["dtype"]
if requested_dtype in (tf.bfloat16, tf.float32):
kwargs["dtype"] = tf.bfloat16
kwargs["initializer"] = _EncodingInitializer(
kwargs["initializer"], self)
ret = self._decode_with_identity_gradie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_videos(template, video_length, frame_shape):
"""Loads videos from files. Args: template: template string for listing the image files. video_length: leng... |
filenames = tf.gfile.Glob(template)
if not filenames:
raise ValueError("no files found.")
filenames = sorted(filenames)
dataset_len = len(filenames)
filenames = tf.constant(filenames)
dataset = tf.data.Dataset.from_tensor_slices(filenames)
dataset = dataset.apply(tf.data.experimental.map_and_batch(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, sh... |
output = tf.cast(output, dtype=tf.int32)
target = tf.cast(target, dtype=tf.int32)
psnr = tf.image.psnr(output, target, max_val=255)
ssim = tf.image.ssim(output, target, max_val=255)
return psnr, ssim |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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-steps
outputs = outputs[:, :num_steps]
targets_placeholder = tf.placeholder(targets.dtype, targets.shap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=(nu... |
num_videos = metrics.shape[1]
# Take mean of the metric across the frames to approximate the video
# closest to the ground truth.
mean_across_frames = np.mean(metrics, axis=-1)
# For every sample, use the decode that has a maximum mean-metric.
best_decode_ind = reduce_func(mean_across_frames, axis=0)
be... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_all_metrics_statistics(all_results):
"""Computes statistics of metrics across multiple decodings. Args: all_results: dict of 3-D numpy arrays. Each a... |
statistics = {}
decode_inds = {}
all_metrics = all_results.keys()
for key in all_metrics:
values = all_results[key]
statistics[key + "_MEAN"] = np.mean(values, axis=0)
statistics[key + "_STD"] = np.std(values, axis=0)
min_stats, min_decode_ind = reduce_to_best_decode(values, np.argmin)
sta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_video_metrics_from_predictions(predictions, decode_hparams):
"""Computes metrics from predictions. Args: predictions: list of list of dicts. outer le... |
all_results = {}
ssim_all_decodes, psnr_all_decodes = [], []
for single_decode in predictions:
args = get_zipped_dataset_from_predictions(single_decode)
psnr_single, ssim_single = compute_one_decoding_video_metrics(*args)
psnr_all_decodes.append(psnr_single)
ssim_all_decodes.append(ssim_single)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_dirs):
save_results(results, output_dir, problem_name)
parent_dir = os.path.join(output_dirs[0], os.pardir)
final_dir = os.path.joi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.float32)
outputs, new_state = cell(inputs, state)
return outputs, new_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=Non... |
input_shape = common_layers.shape_list(inputs)
cell = tf.nn.rnn_cell.LSTMCell(num_units,
use_peepholes=use_peepholes,
cell_clip=cell_clip,
initializer=initializer,
num_proj=num_proj,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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:]
else:
input_shape = spatial_dims + [input_channels]
cell = tf.contrib.rnn.ConvLSTMCell(
2, input_shape, output_channels,
[ker... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scheduled_sample_count(ground_truth_x, generated_x, batch_size, scheduled_sample_var):
"""Sample batch with specified mix of groundtruth and generated data p... |
num_ground_truth = scheduled_sample_var
idx = tf.random_shuffle(tf.range(batch_size))
ground_truth_idx = tf.gather(idx, tf.range(num_ground_truth))
generated_idx = tf.gather(idx, tf.range(num_ground_truth, batch_size))
ground_truth_examps = tf.gather(ground_truth_x, ground_truth_idx)
generated_examps = tf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inject_additional_input(layer, inputs, name, mode="concat"):
"""Injects the additional input into the layer. Args: layer: layer that the input should be inje... |
layer_shape = common_layers.shape_list(layer)
input_shape = common_layers.shape_list(inputs)
zeros_mask = tf.zeros(layer_shape, dtype=tf.float32)
if mode == "concat":
emb = encode_to_shape(inputs, layer_shape, name)
layer = tf.concat(values=[layer, emb], axis=-1)
elif mode == "multiplicative":
fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scheduled_sample_prob(ground_truth_x, generated_x, batch_size, scheduled_sample_var):
"""Probability based scheduled sampling. Args: ground_truth_x: tensor o... |
probability_threshold = scheduled_sample_var
probability_of_generated = tf.random_uniform([batch_size])
return tf.where(probability_of_generated > probability_threshold,
generated_x, ground_truth_x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dna_transformation(prev_image, dna_input, dna_kernel_size, relu_shift):
"""Apply dynamic neural advection to previous image. Args: prev_image: previous image... |
# Construct translated images.
prev_image_pad = tf.pad(prev_image, [[0, 0], [2, 2], [2, 2], [0, 0]])
image_height = int(prev_image.get_shape()[1])
image_width = int(prev_image.get_shape()[2])
inputs = []
for xkern in range(dna_kernel_size):
for ykern in range(dna_kernel_size):
inputs.append(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cdna_transformation(prev_image, cdna_input, num_masks, color_channels, dna_kernel_size, relu_shift):
"""Apply convolutional dynamic neural advection to previ... |
batch_size = tf.shape(cdna_input)[0]
height = int(prev_image.get_shape()[1])
width = int(prev_image.get_shape()[2])
# Predict kernels using linear function of last hidden layer.
cdna_kerns = tfl.dense(
cdna_input, dna_kernel_size * dna_kernel_size * num_masks,
name="cdna_params",
activatio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 net... |
with tf.variable_scope(scope):
net = tfl.conv2d(inputs, nout, kernel_size=kernel_size, padding=padding,
activation=None, name="conv")
if has_batchnorm:
net = tfl.batch_normalization(net, training=is_training, name="bn")
net = activation(net)
return net |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 wid... |
if not concat_latent:
return image
image_shape = common_layers.shape_list(image)
latent_shape = common_layers.shape_list(latent)
height, width = image_shape[1], image_shape[2]
latent_dims = latent_shape[1]
height_multiples = height // latent_dims
pad = height - (height_multiples * latent_dims)
late... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, ... |
writer = WholeVideoWriter(fps)
writer.write_multi(images)
return writer.finish() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
conv_size = tinyify([32, 64, 64], tiny_mode, small_mode)
with tf.variable_scope("latent", reuse=tf.AUTO_REUSE):
images = tf.to_float(images)
images = tf.unstack(images, axis=time_axis)
images = tf.concat(images, axis=3)
x = images
x = common_layers.make_even_size(x)
x = tfl.conv2d(x, conv_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) nu... |
if num_frames == -1:
return videos
batch_size, num_total_frames, h, w, c = common_layers.shape_list(videos)
if num_total_frames < num_frames:
raise ValueError("Expected num_frames <= %d, got %d" %
(num_total_frames, num_frames))
# Randomly choose start_inds for each video.
frame... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_shape
self.cmd = [
ffmpeg, "-y",
"-f", "rawvideo",
"-vcode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
import io # pylint: disable=g-import-not-at-top
import threading # pylint: disable=g-import-not-at-top
def target():
while True:
chunk = stream.read(io.DEFAULT_BUFFER_SIZE)
if not chunk:
break
chunks.append(chunk)
thread = threading.Thread(target=target)
th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, err) = [
b"".join(chunks) for chunks in (self._out_chunks, self._err_chunks)
]
self.proc.stdout.close()
self.proc.stderr.close()
if self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_version)
else:
request_fn = serving_utils.make_grpc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, w... |
latent_dims = self.hparams.z_dim
shape_as_list = inputs.shape.as_list()
if len(shape_as_list) != 5:
raise ValueError("Expected inputs to be a 5-D, got %d" %
len(shape_as_list))
if inputs.dtype != tf.float32:
raise ValueError("Expected dtype tf.float32, got %s" % inpu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_width])
for curr_stride, kernel_size in zip(strides, kernel_sizes):
output_shape = self.expected_output_shape(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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=... |
ndf = self.hparams.num_discriminator_filters
frames = tf.stack(frames)
# Switch from time-major axis to batch-major axis.
frames = common_video.swap_time_and_batch_axes(frames)
# 3-D Conv-net mapping inputs to activations.
num_outputs = [ndf, ndf*2, ndf*2, ndf*4, ndf*4, ndf*8, ndf*8]
kern... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 comp... |
hparam_to_disc_loss = {
"least_squares": gan_losses.least_squares_discriminator_loss,
"cross_entropy": gan_losses.modified_discriminator_loss,
"wasserstein": gan_losses.wasserstein_discriminator_loss}
# Concat across batch-axis.
_, batch_size, _, _, _ = common_layers.shape_list(tru... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: Lo... |
hparam_to_gen_loss = {
"least_squares": gan_losses.least_squares_generator_loss,
"cross_entropy": gan_losses.modified_generator_loss,
"wasserstein": gan_losses.wasserstein_generator_loss
}
fake_logits = self.discriminator(gen_frames)
mean_fake_logits = tf.reduce_mean(fake_logit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
# D - STEP
with tf.variable_scope("%s_discriminator" % name, reuse=tf.AUTO_REUSE):
gan_d_loss, _, fake_logits_stop = self.d_step(
true_frames, gen_frames)
# G - STEP
with tf.variable_scope("%s_discriminator" % name, reuse=True):
gan_g_loss_pos_d, gan_g_loss_neg_d = self.g_step(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.hparams.use_vae:
vae_loss = super(NextFrameSavpBase, self).get_extra_loss(
latent_means=latent_means, latent_stds=latent_stds)
if self.hparams... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 isinstance(strides, numbers.Integral):
strides = [strides] * 3
strides = [1] + strides + [1]
# Filter_shape = [K, K, K, num_input, num_outpu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_params.white_list)
in_blacklist = any(e in name for e in pruning_params.black_list)
if pruning_params.white_li... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
hparams.epochs_num = 1000
hparams.policy_network =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_epochs = 200
hparams.dropout_ppo = 0.1
# The parameters below are modifie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_stochastic_discrete()
for (name, value) in six.iteritems(video_hparams.values()):
if name in hparams_keys:
hparams... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
def env_fn(in_graph):
class_ = SimulatedBatchEnv if in_graph else SimulatedBatchGymEnv
return class_(**env_kwargs)
return env_fn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_size", "intrinsic_reward_scale"])
]
kwargs = {
attr: getattr(obj, attr) # pylint: disable=g-complex-comprehension
for (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_policy(observations, hparams, action_space):
"""Get a policy network. Args: observations: observations hparams: parameters action_space: action space Ret... |
if not isinstance(action_space, gym.spaces.Discrete):
raise ValueError("Expecting discrete action space.")
obs_shape = common_layers.shape_list(observations)
(frame_height, frame_width) = obs_shape[2:4]
# TODO(afrozm): We have these dummy problems mainly for hparams, so cleanup
# when possible and do t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 = 0
hparams.max_num_noops = 0
hparams.rl_should_derive_observati... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
return hparams |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rlmf_dqn_tiny():
"""Tiny DQN params.""" |
hparams = rlmf_original()
hparams = hparams.override_from_dict(rlmf_tiny_overrides())
hparams.batch_size = 1
hparams.base_algo = "dqn"
hparams.base_algo_params = "dqn_original_params"
hparams.add_hparam("dqn_num_frames", 128)
hparams.add_hparam("dqn_save_every_steps", 128)
hparams.add_hparam("dqn_repla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rlmf_eval():
"""Eval set of hparams for model-free PPO.""" |
hparams = rlmf_original()
hparams.batch_size = 8
hparams.eval_sampling_temps = [0.0, 0.5, 1.0]
hparams.eval_rl_env_max_episode_steps = -1
hparams.add_hparam("ppo_epoch_length", 128)
hparams.add_hparam("ppo_optimization_batch_size", 32)
hparams.add_hparam("ppo_epochs_num", 10000)
hparams.add_hparam("ppo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feed_forward_gaussian_fun(action_space, config, observations):
"""Feed-forward Gaussian.""" |
if not isinstance(action_space, gym.spaces.box.Box):
raise ValueError("Expecting continuous action space.")
mean_weights_initializer = tf.initializers.variance_scaling(
scale=config.init_mean_factor)
logstd_initializer = tf.random_normal_initializer(config.init_logstd, 1e-10)
flat_observations = tf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _curvature_range(self):
"""Curvature range. Returns: h_max_t, h_min_t ops """ |
self._curv_win = tf.get_variable("curv_win",
dtype=tf.float32,
trainable=False,
shape=[self.curvature_window_width,],
initializer=tf.zeros_initializer)
# We use lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _grad_variance(self):
"""Estimate of gradient Variance. Returns: C_t ops. """ |
grad_var_ops = []
tensor_to_avg = []
for t, g in zip(self._vars, self._grad):
if isinstance(g, tf.IndexedSlices):
tensor_to_avg.append(
tf.reshape(tf.unsorted_segment_sum(g.values,
g.indices,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dist_to_opt(self):
"""Distance to optimum. Returns: D_t ops """ |
dist_to_opt_ops = []
# Running average of the norm of gradient
self._grad_norm = tf.sqrt(self._grad_norm_squared)
avg_op = self._moving_averager.apply([self._grad_norm,])
dist_to_opt_ops.append(avg_op)
with tf.control_dependencies([avg_op]):
self._grad_norm_avg = self._moving_averager.ave... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _grad_sparsity(self):
"""Gradient sparsity.""" |
# If the sparse minibatch gradient has 10 percent of its entries
# non-zero, its sparsity is 0.1.
# The norm of dense gradient averaged from full dataset
# are roughly estimated norm of minibatch
# sparse gradient norm * sqrt(sparsity)
# An extension maybe only correct the sparse blob.
non_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_variables(self):
"""Prepare Variables for YellowFin. Returns: Grad**2, Norm, Norm**2, Mean(Norm**2) ops """ |
self._moving_averager = tf.train.ExponentialMovingAverage(
decay=self._beta, zero_debias=self._zero_debias)
# assert self._grad is not None and len(self._grad) > 0
# List for the returned Operations
prepare_variables_op = []
# Get per var g**2 and norm**2
self._grad_squared = []
se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_cubic_root(self):
"""Get the cubic root.""" |
# We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2
# where x = sqrt(mu).
# We substitute x, which is sqrt(mu), with x = y + 1.
# It gives y^3 + py = q
# where p = (D^2 h_min^2)/(2*C) and q = -p.
# We use the Vieta's substitution to compute the root.
# There is only one real solution y (... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_lr_tensor(self):
"""Get lr minimizing the surrogate. Returns: The lr_t. """ |
lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min
return lr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_mu_tensor(self):
"""Get the min mu which minimize the surrogate. Returns: The mu_t. """ |
root = self._get_cubic_root()
dr = self._h_max / self._h_min
mu = tf.maximum(
root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2)
return mu |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _yellowfin(self):
"""YellowFin auto-tuning optimizer based on momentum SGD. Returns: YF ops (Curvature range, Grad_variance, Dist_to_opt, Single-Step, Auto-T... |
# List for the returned Operations.
yellowfin_ops = []
# Curvature range ops.
curv_range_ops = self._curvature_range()
yellowfin_ops += curv_range_ops
# Estimate of gradient Variance ops.
grad_var_ops = self._grad_variance()
yellowfin_ops += grad_var_ops
# Distance to optimum ops.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""Applying gradients and tune hyperparams with YellowFin. Args: grads_and_vars: List of ... |
self._grad, self._vars = zip(*[(g, t)
for g, t in grads_and_vars if g is not None])
# Var update with Momentum.
with tf.variable_scope("apply_updates"):
# Gradient Clipping?
if self._clip_thresh_var is not None:
self._grad, _ = tf.clip_by_global_norm(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_gradients(self, loss, var_list, global_step=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_... |
del global_step, name # Unused for now.
return self._momentum_optimizer.compute_gradients(
loss,
var_list=var_list,
gate_gradients=gate_gradients,
aggregation_method=aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
grad_loss=grad_loss... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def minimize(self, loss, global_step=None, var_list=None, gate_gradients=GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss... |
grads_and_vars = self._momentum_optimizer.compute_gradients(
loss,
var_list=var_list,
gate_gradients=gate_gradients,
aggregation_method=aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
grad_loss=grad_loss)
vars_with_grad = [v for g, v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bytenet_internal(inputs, targets, hparams):
"""ByteNet, main step used for training.""" |
with tf.variable_scope("bytenet"):
# Flatten inputs and extend length by 50%.
inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2)
extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1]))
inputs_shape = inputs.shape.as_list()
inputs = tf.pad(inputs, [[0, 0], [0, extend_le... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _download_and_parse_dataset(tmp_dir, train):
"""Downloads and prepairs the dataset to be parsed by the data_generator.""" |
file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL)
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(tmp_dir)
zip_ref.close()
file_name = 'train' if train else 'dev'
dataset_file_path = os.path.join(tmp_dir, _SNLI_DATA_PATH % file_name)
_parse_dataset(dataset_file_path,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_tokens_and_tags(parse_str):
"""Parse str to tokens and pos tags.""" |
tokens = []
parse_split = parse_str.split(' ')
for p in parse_split:
assert p.startswith('(') or p.endswith(')')
if p.endswith(')'):
token = p.replace(')', '')
tokens.append(token)
return tokens |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_dataset(file_path, tmp_dir, train):
"""Convert the dataset in to a simpler format. This function creates two files. One for being processed to produce... |
input_path = file_path
file_name = 'train' if train else 'dev'
gen_output_path = os.path.join(tmp_dir, file_name + '.txt')
example_output_path = os.path.join(tmp_dir, _EXAMPLES_FILE)
print('input path: ' + input_path)
print('gen_output_path: ' + gen_output_path)
print('example_output_path: ' + example_o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_or_generate_vocab(tmp_dir, vocab_filename, vocab_size):
"""Read or create vocabulary.""" |
vocab_filepath = os.path.join(tmp_dir, vocab_filename)
print('Vocab file written to: ' + vocab_filepath)
if tf.gfile.Exists(vocab_filepath):
gs = text_encoder.SubwordTextEncoder(vocab_filepath)
return gs
example_file = os.path.join(tmp_dir, _EXAMPLES_FILE)
gs = text_encoder.SubwordTextEncoder()
to... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shard(items, num_shards):
"""Split items into num_shards groups.""" |
sharded = []
num_per_shard = len(items) // num_shards
start = 0
for _ in range(num_shards):
sharded.append(items[start:start + num_per_shard])
start += num_per_shard
remainder = len(items) % num_shards
start = len(items) - remainder
for i in range(remainder):
sharded[i].append(items[start + ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def RandomNormalInitializer(stddev=1e-2):
"""An initializer function for random normal coefficients.""" |
def init(shape, rng):
return (stddev * backend.random.normal(rng, shape)).astype('float32')
return init |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)):
"""An initializer function for random Glorot-scaled coefficients.""" |
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
size = onp.prod(onp.delete(shape, [in_dim, out_dim]))
std = scale / np.sqrt((fan_in + fan_out) / 2. * size)
return (std * backend.random.normal(rng, shape)).astype('float32')
return init |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GlorotUniformInitializer(out_dim=0, in_dim=1):
"""An initializer function for random uniform Glorot-scaled coefficients.""" |
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
std = np.sqrt(2.0 / (fan_in + fan_out))
a = np.sqrt(3.0) * std
return backend.random.uniform(rng, shape, minval=-a, maxval=a)
return init |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def one_hot(x, size, dtype=np.float32):
"""Make a n+1 dim one-hot array from n dim int-categorical array.""" |
return np.array(x[..., np.newaxis] == np.arange(size), dtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padtype_to_pads(in_shape, window_shape, window_strides, padding):
"""Convert padding string to list of pairs of pad values.""" |
padding = padding.upper()
if padding == 'SAME':
out_shape = onp.ceil(
onp.true_divide(in_shape, window_strides)).astype(int)
pad_sizes = [max((out_size - 1) * stride + window_shape - in_size, 0)
for out_size, stride, window_shape, in_size
in zip(out_shape, window_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _flatten_output_shape(input_shape, num_axis_to_keep=1):
"""Output shape of a flatten layer.""" |
if num_axis_to_keep >= len(input_shape):
raise ValueError(
"num_axis_to_keep[%d] should be less than input's rank[%d]" %
(num_axis_to_keep, len(input_shape)))
return tuple(input_shape[:num_axis_to_keep]) + (
reduce(op.mul, input_shape[num_axis_to_keep:], 1),) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2), center=True, scale=True, **kwargs):
"""Helper to initialize batch norm params.""" |
del rng, kwargs
axis = (axis,) if np.isscalar(axis) else axis
shape = tuple(d for i, d in enumerate(input_shape) if i not in axis)
beta = np.zeros(shape, dtype='float32') if center else ()
gamma = np.ones(shape, dtype='float32') if scale else ()
return (beta, gamma) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5, center=True, scale=True, **unused_kwargs):
"""Layer construction function for a batch normalization layer.... |
mean = np.mean(x, axis, keepdims=True)
# Fast but less numerically-stable variance calculation than np.var.
m1 = np.mean(x**2, axis, keepdims=True)
var = m1 - mean**2
z = (x - mean) / np.sqrt(var + epsilon)
# Expand the parameters to have the right axes.
beta, gamma = params
# TODO(phawkins): np.expan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.