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 _pool_one_shape(features_2d, area_width, area_height, batch_size, width, height, depth, fn=tf.reduce_max, name=None):
"""Pools for an area in features_2d. Ar... |
with tf.name_scope(name, default_name="pool_one_shape"):
images = []
for y_shift in range(area_height):
image_height = tf.maximum(height - area_height + 1 + y_shift, 0)
for x_shift in range(area_width):
image_width = tf.maximum(width - area_width + 1 + x_shift, 0)
area = features_... |
<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_area_features(features, max_area_width, max_area_height=1, height=1, epsilon=1e-6):
"""Computes features for each area. Args: features: a Tensor in a... |
with tf.name_scope("compute_area_features"):
tf.logging.info("area_attention compute_area_features: %d x %d",
max_area_height, max_area_width)
area_sum, area_heights, area_widths = _compute_sum_image(
features, max_area_width=max_area_width,
max_area_height=max_area_height... |
<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_area_key(features, max_area_width, max_area_height=1, height=1, mode="mean", training=True, name=None):
"""Computes the key for each area. Args: feat... |
tf.logging.info("area_attention mode=%s", mode)
area_mean, area_std, _, area_heights, area_widths =\
compute_area_features(features, max_area_width=max_area_width,
max_area_height=max_area_height, height=height)
if mode == "mean":
return area_mean
elif mode == "max":
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_directories(base_dir, subdirs):
"""Setup directories.""" |
base_dir = os.path.expanduser(base_dir)
tf.gfile.MakeDirs(base_dir)
all_dirs = {}
for subdir in subdirs:
if isinstance(subdir, six.string_types):
subdir_tuple = (subdir,)
else:
subdir_tuple = subdir
dir_name = os.path.join(base_dir, *subdir_tuple)
tf.gfile.MakeDirs(dir_name)
al... |
<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_relative_timing_fn():
"""Make a function that logs the duration since it was made.""" |
start_time = time.time()
def format_relative_time():
time_delta = time.time() - start_time
return str(datetime.timedelta(seconds=time_delta))
def log_relative_time():
tf.logging.info("Timing: %s", format_relative_time())
return log_relative_time |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def train_supervised(problem, model_name, hparams, data_dir, output_dir, train_steps, eval_steps, local_eval_frequency=None, schedule="continuous_train_and_eval")... |
if local_eval_frequency is None:
local_eval_frequency = FLAGS.local_eval_frequency
exp_fn = trainer_lib.create_experiment_fn(
model_name, problem, data_dir, train_steps, eval_steps,
min_eval_frequency=local_eval_frequency
)
run_config = trainer_lib.create_run_config(model_name, model_dir=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 train_agent(real_env, learner, world_model_dir, hparams, epoch):
"""Train the PPO agent in the simulated environment.""" |
initial_frame_chooser = rl_utils.make_initial_frame_chooser(
real_env, hparams.frame_stack_size, hparams.simulation_random_starts,
hparams.simulation_flip_first_random_for_beginning
)
env_fn = rl.make_simulated_env_fn_from_hparams(
real_env, hparams, batch_size=hparams.simulated_batch_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 train_agent_real_env(env, learner, hparams, epoch):
"""Train the PPO agent in the real environment.""" |
base_algo_str = hparams.base_algo
train_hparams = trainer_lib.create_hparams(hparams.base_algo_params)
rl_utils.update_hparams_from_hparams(
train_hparams, hparams, "real_" + base_algo_str + "_"
)
if hparams.wm_policy_param_sharing:
train_hparams.optimizer_zero_grads = True
env_fn = rl.make_rea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def train_world_model( env, data_dir, output_dir, hparams, world_model_steps_num, epoch ):
"""Train the world model on problem_name.""" |
world_model_steps_num += world_model_step_increment(
hparams, is_initial_epoch=(epoch == 0)
)
model_hparams = trainer_lib.create_hparams(hparams.generative_model_params)
model_hparams.learning_rate = model_hparams.learning_rate_constant
if epoch > 0:
model_hparams.learning_rate *= hparams.learning_... |
<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_metrics(event_dir, epoch):
"""Loads metrics for this epoch if they have already been written. This reads the entire event file but it's small with just ... |
metrics = {}
for filename in tf.gfile.ListDirectory(event_dir):
path = os.path.join(event_dir, filename)
for event in tf.train.summary_iterator(path):
if event.step == epoch and event.HasField("summary"):
value = event.summary.value[0]
metrics[value.tag] = value.simple_value
return ... |
<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_layer(x, hidden_size, kernel_size, stride, pooling_window, dropout_rate, dilation_rate, name="conv"):
"""Single conv layer with relu, optional pooling, ... |
with tf.variable_scope(name):
out = x
out = common_layers.conv1d_block(
out,
hidden_size, [(dilation_rate, kernel_size)],
strides=stride,
first_relu=False,
padding="same")
out = tf.nn.relu(out)
if pooling_window:
out = tf.layers.max_pooling1d(
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 gene_expression_conv_base():
"""Hparams for GeneExpressionConv model.""" |
hparams = common_hparams.basic_params1()
batch_size = 10
output_length = 2048
inputs_per_output = 128
chunk_size = 4
input_length = output_length * inputs_per_output // chunk_size
hparams.batch_size = input_length * batch_size
hparams.dropout = 0.1
hparams.add_hparam("num_conv_layers", 4)
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 compress_self_attention_layer(x, hparams, name=None):
"""Attend function.""" |
with tf.variable_scope(name, default_name="compress_self_attention"):
x, xshape, _ = cia.maybe_reshape_4d_to_3d(x)
y = common_attention.multihead_attention(
common_layers.layer_preprocess(x, hparams),
None,
None,
hparams.attention_key_channels or hparams.hidden_size,
h... |
<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_nats_and_bits_per_dim(data_dim, latent_dim, average_reconstruction, average_prior):
"""Computes negative ELBO, which is an upper bound on the negativ... |
with tf.name_scope(None, default_name="compute_nats_per_dim"):
data_dim = tf.cast(data_dim, average_reconstruction.dtype)
latent_dim = tf.cast(latent_dim, average_prior.dtype)
negative_log_likelihood = data_dim * average_reconstruction
negative_log_prior = latent_dim * average_prior
negative_elbo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multinomial_sample(x, vocab_size=None, sampling_method="random", temperature=1.0):
"""Multinomial sampling from a n-dimensional tensor. Args: vocab_size: Num... |
vocab_size = vocab_size or common_layers.shape_list(x)[-1]
if sampling_method == "random" and temperature > 0.0:
samples = tf.multinomial(tf.reshape(x, [-1, vocab_size]) / temperature, 1)
else:
samples = tf.argmax(x, axis=-1)
reshaped_samples = tf.reshape(samples, common_layers.shape_list(x)[:-1])
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ae_latent_sample_beam(latents_dense_in, inputs, ed, embed, hparams):
"""Samples from the latent space in the autoencoder. Args: its first two dimensions are ... |
def symbols_to_logits_fn(ids):
"""Go from ids to logits."""
ids = tf.expand_dims(ids, axis=2) # Ids start with added all-zeros.
latents_discrete = tf.pad(ids[:, 1:], [[0, 0], [0, 1], [0, 0]])
with tf.variable_scope(tf.get_variable_scope(), reuse=False):
latents_dense = embed(
tf.on... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def residual_block_layer(inputs, hparams):
"""Residual block over inputs. Runs a residual block consisting of conv: kernel_size x kernel_size conv: 1x1 dropout, ... |
kernel = (hparams.res_kernel_size, hparams.res_kernel_size)
x = inputs
for i in range(hparams.num_res_layers):
with tf.variable_scope("res_conv_%d" % i):
# kernel_size x kernel_size conv block
y = common_layers.conv_block(
common_layers.layer_norm(x, hparams.hidden_size, name="lnorm"),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transformer_text_encoder(inputs, target_space, hparams, name=None):
"""Transformer text encoder over inputs with unmasked full attention. Args: inputs: Tenso... |
with tf.variable_scope(name, default_name="transformer_text_encoder"):
inputs = common_layers.flatten4d3d(inputs)
[
encoder_input,
encoder_self_attention_bias,
ed,
] = transformer_layers.transformer_prepare_encoder(
inputs, target_space=target_space, hparams=hparams)
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 transformer_image_decoder(targets, encoder_output, ed_attention_bias, hparams, name=None):
"""Transformer image decoder over targets with local attention. Ar... |
with tf.variable_scope(name, default_name="transformer_dec"):
batch_size = common_layers.shape_list(targets)[0]
targets = tf.reshape(targets, [batch_size,
hparams.img_len,
hparams.img_len,
hparams.num_cha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transformer_latent_decoder(x, encoder_output, ed_attention_bias, hparams, name=None):
"""Transformer decoder over latents using latent_attention_type. Args: ... |
with tf.variable_scope(name, default_name="transformer_latent_dec"):
batch_size = common_layers.shape_list(x)[0]
compressed_img_len = (hparams.img_len //
2**(hparams.num_compress_steps // 2))
x = tf.reshape(x, [batch_size,
compressed_img_len,
... |
<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_prediction_model(inputs, ed_attention_bias, latents_discrete, latents_dense, hparams, vocab_size=None, name=None):
"""Transformer-based latent predict... |
with tf.variable_scope(name, default_name="latent_prediction"):
if hparams.mode != tf.estimator.ModeKeys.PREDICT:
latents_pred = transformer_latent_decoder(tf.stop_gradient(latents_dense),
inputs,
ed_attention_b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iaf_flow(one_hot_assignments, scale_weights, scale_bias, num_codes, summary=True, name=None):
"""Performs a single IAF flow using scale and normalization tra... |
with tf.name_scope(name, default_name="iaf"):
# Pad the one_hot_assignments by zeroing out the first latent dimension and
# shifting the rest down by one (and removing the last dimension).
padded_assignments = tf.pad(
one_hot_assignments, [[0, 0], [0, 0], [1, 0], [0, 0]])[:, :, :-1, :]
scale_... |
<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_lsun(directory, category, split_name):
"""Downloads all lsun files to directory unless they are there.""" |
generator_utils.maybe_download(directory,
_LSUN_DATA_FILENAME % (category, split_name),
_LSUN_URL % (category, split_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 _mixed_precision_is_enabled(hparams):
"""Should be the same as in common_attention, avoiding import.""" |
activation_dtype = hparams.activation_dtype
weight_dtype = hparams.weight_dtype
return activation_dtype == tf.float16 and weight_dtype == tf.float32 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optimize(loss, learning_rate, hparams, use_tpu=False, variables=None):
"""Minimize loss.""" |
loss = weight_decay_and_noise(loss, hparams, learning_rate)
loss = tf.identity(loss, name="total_loss")
if variables is None:
variables = tf.trainable_variables()
# Print trainable variables.
log_variable_sizes(variables, verbose=hparams.summarize_vars)
# Print non-trainable variables.
non_trainable_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def weight_decay_and_noise(loss, hparams, learning_rate, var_list=None):
"""Apply weight decay and weight noise.""" |
if var_list is None:
var_list = tf.trainable_variables()
decay_vars = [v for v in var_list]
noise_vars = [v for v in var_list if "/body/" in v.name]
weight_decay_loss = weight_decay(hparams.weight_decay, decay_vars)
if hparams.weight_decay and common_layers.should_generate_summaries():
tf.summary.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 weight_noise(noise_rate, learning_rate, var_list):
"""Apply weight noise to vars in var_list.""" |
if not noise_rate:
return [tf.no_op()]
tf.logging.info("Applying weight noise scaled by learning rate, "
"noise_rate: %0.5f", noise_rate)
noise_ops = []
for v in var_list:
with tf.device(v.device): # pylint: disable=protected-access
scale = noise_rate * learning_rate * 0.001... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def weight_decay(decay_rate, var_list, skip_biases=True):
"""Apply weight decay to vars in var_list.""" |
if not decay_rate:
return 0.
tf.logging.info("Applying weight decay, decay_rate: %0.5f", decay_rate)
weight_decays = []
for v in var_list:
# Weight decay.
# This is a heuristic way to detect biases that works for main tf.layers.
is_bias = len(v.shape.as_list()) == 1 and v.name.endswith("bias:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summarize_variables(var_list=None, tag=None):
"""Summarize the variables. Args: var_list: a list of variables; defaults to trainable_variables. tag: name sco... |
if var_list is None:
var_list = tf.trainable_variables()
if tag is None:
tag = "training_variables/"
name_to_var = {v.name: v for v in var_list}
for v_name in list(name_to_var):
v = name_to_var[v_name]
tf.summary.histogram(tag + v_name, 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 get_variable_initializer(hparams):
"""Get variable initializer from hparams.""" |
if not hparams.initializer:
return None
mlperf_log.transformer_print(key=mlperf_log.MODEL_HP_INITIALIZER_GAIN,
value=hparams.initializer_gain,
hparams=hparams)
if not tf.executing_eagerly():
tf.logging.info("Using variable initializer: %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 summarize_tensors(tensor_dict, tag=None):
"""Summarize the tensors. Args: tensor_dict: a dictionary of tensors. tag: name scope of the summary; defaults to t... |
if tag is None:
tag = "tensors/"
for t_name in list(tensor_dict):
t = tensor_dict[t_name]
tf.summary.histogram(tag + t_name, t) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def image_embedding(images, model_fn=resnet_v1_152, trainable=True, is_training=True, weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_... |
is_resnet_training = trainable and is_training
batch_norm_params = {
"is_training": is_resnet_training,
"trainable": trainable,
"decay": batch_norm_decay,
"epsilon": batch_norm_epsilon,
"scale": batch_norm_scale,
}
if trainable:
weights_regularizer = tf.contrib.layers.l2_re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timit_generator(data_dir, tmp_dir, training, how_many, start_from=0, eos_list=None, vocab_filename=None, vocab_size=0):
"""Data generator for TIMIT transcrip... |
del data_dir
eos_list = [1] if eos_list is None else eos_list
if vocab_filename is not None:
# TODO(lukaszkaiser): Correct this call to generate a vocabulary. No data
# sources are being passed.
# vocab_symbolizer = generator_utils.get_or_generate_vocab(
# data_dir, tmp_dir, vocab_filename, 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 _build_vocab(filename, vocab_dir, vocab_name):
"""Reads a file to build a vocabulary. Args: filename: file to read list of words from. vocab_dir: directory w... |
vocab_path = os.path.join(vocab_dir, vocab_name)
if not tf.gfile.Exists(vocab_path):
with tf.gfile.GFile(filename, "r") as f:
data = f.read().split()
counter = collections.Counter(data)
count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
words, _ = list(zip(*count_pairs))
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 aligned_8k_grouped():
"""version for languagemodel_wiki_scramble8k50. languagemodel_wiki_scramble1k50, 1gpu, 7k steps: log(ppl)_eval = 2.92 3.3 steps/sec on ... |
hparams = aligned_grouped()
hparams.batch_size = 8192
# hparams.attention_image_summary = False
hparams.num_groups = 16
hparams.multiplicative_overhead = 1.1
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 _expand_to_beam_size(tensor, beam_size):
"""Tiles a given tensor by beam_size. Args: beam_size: How much to tile the tensor by. Returns: """ |
tensor = tf.expand_dims(tensor, axis=1)
tile_dims = [1] * tensor.shape.ndims
tile_dims[1] = beam_size
return tf.tile(tensor, tile_dims) |
<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_state_shape_invariants(tensor):
"""Returns the shape of the tensor but sets middle dims to None.""" |
shape = tensor.shape.as_list()
for i in range(1, len(shape) - 1):
shape[i] = None
return tf.TensorShape(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 compute_batch_indices(batch_size, beam_size):
"""Computes the i'th coordinate that contains the batch index for gathers. Batch pos is a tensor like [[0,0,0,0... |
batch_pos = tf.range(batch_size * beam_size) // beam_size
batch_pos = tf.reshape(batch_pos, [batch_size, beam_size])
return batch_pos |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fast_tpu_gather(params, indices, name=None):
"""Fast gather implementation for models running on TPU. This function use one_hot and batch matmul to do gather... |
with tf.name_scope(name):
dtype = params.dtype
def _gather(params, indices):
"""Fast gather using one_hot and batch matmul."""
if dtype != tf.float32:
params = tf.to_float(params)
shape = common_layers.shape_list(params)
indices_shape = common_layers.shape_list(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 _create_make_unique(inputs):
"""Replaces the lower bits of each element with iota. The iota is used to derive the index, and also serves the purpose to make ... |
if inputs.shape.ndims != 2:
raise ValueError("Input of top_k_with_unique must be rank-2 "
"but got: %s" % inputs.shape)
height = inputs.shape[0]
width = inputs.shape[1]
zeros = tf.zeros([height, width], dtype=tf.int32)
# Count_mask is used to mask away the low order bits to ensure ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_topk_unique(inputs, k):
"""Creates the top k values in sorted order with indices. Args: inputs: A tensor with rank of 2. [batch_size, original_size].... |
height = inputs.shape[0]
width = inputs.shape[1]
neg_inf_r0 = tf.constant(-np.inf, dtype=tf.float32)
ones = tf.ones([height, width], dtype=tf.float32)
neg_inf_r2 = ones * neg_inf_r0
inputs = tf.where(tf.is_nan(inputs), neg_inf_r2, inputs)
# Select the current largest value k times and keep them in topk_... |
<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_k_with_unique(inputs, k):
"""Finds the values and indices of the k largests entries. Instead of doing sort like tf.nn.top_k, this function finds the max ... |
unique_inputs = _create_make_unique(tf.cast(inputs, tf.float32))
top_values, indices = _create_topk_unique(unique_inputs, k)
top_values = tf.cast(top_values, inputs.dtype)
return top_values, indices |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def video_augmentation(features, hue=False, saturate=False, contrast=False):
"""Augments video with optional hue, saturation and constrast. Args: features: dict,... |
inputs, targets = features["inputs"], features["targets"]
in_steps = common_layers.shape_list(inputs)[0]
# makes sure that the same augmentation is applied to both input and targets.
# if input is 4-D, then tf.image applies the same transform across the batch.
video = tf.concat((inputs, targets), axis=0)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_border(video, color="blue", border_percent=2):
"""Creates a border around each frame to differentiate input and target. Args: video: 5-D NumPy array. ... |
# Do not create border if the video is not in RGB format
if video.shape[-1] != 3:
return video
color_to_axis = {"blue": 2, "red": 0, "green": 1}
axis = color_to_axis[color]
_, _, height, width, _ = video.shape
border_height = np.ceil(border_percent * height / 100.0).astype(np.int)
border_width = np.c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_videos_to_summaries(input_videos, output_videos, target_videos, tag, decode_hparams, display_ground_truth=False):
"""Converts input, output and targe... |
fps = decode_hparams.frames_per_second
border_percent = decode_hparams.border_percent
max_outputs = decode_hparams.max_display_outputs
target_steps = target_videos.shape[1]
all_summaries = []
input_videos = create_border(
input_videos, color="blue", border_percent=border_percent)
target_videos = cr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display_video_hooks(hook_args):
"""Hooks to display videos at decode time.""" |
predictions = hook_args.predictions
max_outputs = hook_args.decode_hparams.max_display_outputs
max_decodes = hook_args.decode_hparams.max_display_decodes
with tf.Graph().as_default():
_, best_decodes = video_metrics.compute_video_metrics_from_predictions(
predictions, decode_hparams=hook_args.deco... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summarize_video_metrics(hook_args):
"""Computes video metrics summaries using the decoder output.""" |
problem_name = hook_args.problem.name
current_problem = hook_args.problem
hparams = hook_args.hparams
output_dirs = hook_args.output_dirs
predictions = hook_args.predictions
frame_shape = [
current_problem.frame_height, current_problem.frame_width,
current_problem.num_channels
]
metrics_gra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug_video_writer_factory(output_dir):
"""Creates a VideoWriter for debug videos.""" |
if FLAGS.disable_ffmpeg:
return common_video.IndividualFrameWriter(output_dir)
else:
output_path = os.path.join(output_dir, "video.avi")
return common_video.WholeVideoWriter(
fps=10, output_path=output_path, file_format="avi"
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""Generate samples of the encoded frames with possible extra data. By default this functio... |
writer = None
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(None, None, None))
encoded_image_t = tf.image.encode_png(image_t)
with tf.Session() as sess:
for features in self.generate_samples(data_dir, tmp_dir, dataset_split):
unencoded_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 generate_data(self, data_dir, tmp_dir, task_id=-1):
"""The function generating the data.""" |
filepath_fns = {
problem.DatasetSplit.TRAIN: self.training_filepaths,
problem.DatasetSplit.EVAL: self.dev_filepaths,
problem.DatasetSplit.TEST: self.test_filepaths,
}
# We set shuffled=True as we don't want to shuffle on disk later.
split_paths = [(split["split"], filepath_fns[... |
<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_variable_proxy_methods(var, proxy_tensor):
"""Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm... |
proxy_tensor.read_value = lambda: tf.identity(proxy_tensor)
proxy_tensor.assign_sub = var.assign_sub
proxy_tensor.assign = var.assign
proxy_tensor.initialized_value = var.initialized_value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rowwise_unsorted_segment_sum(values, indices, n):
"""UnsortedSegmentSum on each row. Args: values: a `Tensor` with shape `[batch_size, k]`. indices: an inte... |
batch, k = tf.unstack(tf.shape(indices), num=2)
indices_flat = tf.reshape(indices, [-1]) + tf.div(tf.range(batch * k), k) * n
ret_flat = tf.unsorted_segment_sum(
tf.reshape(values, [-1]), indices_flat, batch * n)
return tf.reshape(ret_flat, [batch, n]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prob_in_top_k( clean_values, noisy_values, noise_stddev, noisy_top_values, k):
"""Helper function to NoisyTopKGating. Computes the probability that value is... |
batch = tf.shape(clean_values)[0]
m = tf.shape(noisy_top_values)[1]
top_values_flat = tf.reshape(noisy_top_values, [-1])
# we want to compute the threshold that a particular value would have to
# exceed in order to make the top k. This computation differs depending
# on whether the value is already in 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 cv_squared(x):
"""The squared coefficient of variation of a sample. Useful as a loss to encourage a positive distribution to be more uniform. Epsilons added ... |
epsilon = 1e-10
float_size = tf.to_float(tf.size(x)) + epsilon
mean = tf.reduce_sum(x) / float_size
variance = tf.reduce_sum(tf.squared_difference(x, mean)) / float_size
return variance / (tf.square(mean) + epsilon) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_hparams_for_vq_gating(hparams):
"""VQ Gating hparams.""" |
hparams.add_hparam("z_size", 4)
hparams.add_hparam("noise_dev", 0.5)
# Bottleneck kinds supported: dense, vae, dvq.
hparams.add_hparam("bottleneck_kind", "dvq")
hparams.add_hparam("num_blocks", 1)
hparams.add_hparam("num_residuals", 1)
# Reshape method for DVQ: slice, project
hparams.add_hparam("beta",... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _my_top_k(x, k):
"""GPU-compatible version of top-k that works for very small constant k. Calls argmax repeatedly. tf.nn.top_k is implemented for GPU, but th... |
if k > 10:
return tf.nn.top_k(x, k)
values = []
indices = []
depth = tf.shape(x)[1]
for i in range(k):
values.append(tf.reduce_max(x, 1))
argmax = tf.argmax(x, 1)
indices.append(argmax)
if i + 1 < k:
x += tf.one_hot(argmax, depth, -1e9)
return tf.stack(values, axis=1), tf.to_int32... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vq_gating(x, num_experts, k, bneck, hparams=None, name="vq_gating"):
"""VQ gating. Args: x: input Tensor with shape [batch_size, input_size] num_experts: an ... |
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
if hparams.use_scales:
scales = tf.get_variable(
"scales", [num_experts],
tf.float32,
initializer=tf.ones_initializer())
scales = tf.nn.softmax(scales)
hparams.scales = scales
input_size = x.get_shape().as_lis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def noisy_top_k_gating(x, num_experts, train, k=2, initializer=tf.zeros_initializer(), noisy_gating=True, noise_epsilon=1e-2, name=None):
"""Noisy top-k gating. ... |
with tf.variable_scope(name, default_name="noisy_top_k_gating"):
input_size = x.get_shape().as_list()[-1]
w_gate = tf.get_variable(
"w_gate", [input_size, num_experts], tf.float32, initializer)
if noisy_gating:
w_noise = tf.get_variable("w_noise",
[input_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 map_ids(x, indices, map_fn):
"""Apply a function to each coordinate ids of a multidimensional tensor. This allows to process each sequence of a batch indepen... |
indices = tf.reshape(indices, [-1])
t_i = tf.constant(0)
# batch_coordinates start at 0
t_batch_size = tf.reduce_max(indices) + 1
# ta_stack_out will store the intermediate results for each individual id
# As alternative to tf.TensorArray, scatter_update could potentially be used
# but that would requi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ffn_expert_fn(input_size, hidden_sizes, output_size, hidden_activation=tf.nn.relu):
"""Returns a function that creates a feed-forward network. Use this funct... |
def my_fn(x):
layer_sizes = [input_size] + hidden_sizes + [output_size]
for i in range(1 + len(hidden_sizes)):
w = tf.get_variable("w_%d" % i, layer_sizes[i:i+2], tf.float32)
x = tf.matmul(x, w)
if i < len(hidden_sizes):
x = hidden_activation(x)
if layer_sizes[i] != input_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 flatten_all_but_last(a):
"""Flatten all dimensions of a except the last.""" |
ret = tf.reshape(a, [-1, tf.shape(a)[-1]])
if not tf.executing_eagerly():
ret.set_shape([None] + a.get_shape().as_list()[-1:])
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 local_moe(x, train, expert_fn, num_experts, k=1, loss_coef=1e-2, hparams=None, pass_x=True, pass_gates=False, additional_dispatch_params=None, name=None):
""... |
bneck = DiscreteBottleneck(hparams)
with tf.variable_scope(name, default_name="local_moe"):
centroids = None
x_flat = flatten_all_but_last(x)
if hparams.gating_type == "topk":
tf.logging.info("Using noisy top_k with k = {}".format(k))
# The gates indicate which batch elements go to which te... |
<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_by_device(parallelism, data, reduce_fn):
"""Reduces data per device. This can be useful, for example, if we want to all-reduce n tensors on k<n device... |
unique_devices = []
device_to_data = {}
for dev, datum in zip(parallelism.devices, data):
if dev not in device_to_data:
unique_devices.append(dev)
device_to_data[dev] = [datum]
else:
device_to_data[dev].append(datum)
device_parallelism = Parallelism(unique_devices)
grouped_data = [d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True):
"""Compute the sum of all Tensors and put the result everywhere. Assumes that the devi... |
if parallelism.n == 1:
return x
if maybe_reduce:
original_parallelism = parallelism
parallelism, x = reduce_by_device(parallelism, x, tf.add_n)
if parallelism.n == 1:
y = x
else:
# first shard the input:
x_flat = parallelism(tf.reshape, x, [[-1]] * parallelism.n)
# [device, shard]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _maybe_repeat(self, x):
"""Utility function for processing arguments that are singletons or lists. Args: x: either a list of self.n elements, or not a list. ... |
if isinstance(x, list):
assert len(x) == self.n
return x
else:
return [x] * self.n |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, x):
"""Remove padding from the given tensor. Args: Returns: """ |
with tf.name_scope("pad_reduce/remove"):
x_shape = x.get_shape().as_list()
x = tf.gather_nd(
x,
indices=self.nonpad_ids,
)
if not tf.executing_eagerly():
# This is a hack but for some reason, gather_nd return a tensor of
# undefined shape, so the shape is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore(self, x):
"""Add padding back to the given tensor. Args: Returns: dim is restored from the original reference tensor """ |
with tf.name_scope("pad_reduce/restore"):
x = tf.scatter_nd(
indices=self.nonpad_ids,
updates=x,
shape=tf.concat([self.dim_origin, tf.shape(x)[1:]], axis=0),
)
return 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 combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, weighted by the gates. The slice corresponding to a particular batch el... |
# see comments on convert_gradient_to_tensor
stitched = common_layers.convert_gradient_to_tensor(
tf.concat(expert_out, 0))
if multiply_by_gates:
stitched *= tf.expand_dims(self._nonzero_gates, 1)
combined = tf.unsorted_segment_sum(stitched, self._batch_index,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expert_to_batch_indices(self):
"""Batch indices corresponding to the examples in the per-expert `Tensor`s. Returns: a list of `num_experts` one-dimensional `... |
return tf.split(
self._batch_index, self._part_sizes_tensor, 0, num=self._num_experts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, multiplied by the corresponding gates. Args: expert_out: a list of `num... |
expert_part_sizes = tf.unstack(
tf.stack([d.part_sizes for d in self._dispatchers]),
num=self._ep.n,
axis=1)
# list of lists of shape [num_experts][num_datashards]
expert_output_parts = self._ep(tf.split, expert_out, expert_part_sizes)
expert_output_parts_t = transpose_list_of_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 dispatch(self, inp):
"""Send the inputs to the experts. Args: inp: a `Tensor` of shape "[batch, length, depth]` Returns: a tensor with shape [batch, num_expe... |
inp = tf.reshape(inp, [self._batch * self._length, -1])
# [batch, num_experts, expert_capacity, depth]
ret = tf.gather(inp, self._flat_indices)
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 combine(self, x):
"""Return the output from the experts. When one example goes to multiple experts, the outputs are summed. Args: x: a Tensor with shape [bat... |
depth = tf.shape(x)[-1]
x *= tf.expand_dims(self._nonpadding, -1)
ret = tf.unsorted_segment_sum(
x, self._flat_indices, num_segments=self._batch * self._length)
ret = tf.reshape(ret, [self._batch, self._length, depth])
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 make_env(env_type, real_env, sim_env_kwargs):
"""Factory function for envs.""" |
return {
"real": lambda: real_env.new_like( # pylint: disable=g-long-lambda
batch_size=sim_env_kwargs["batch_size"],
store_rollouts=False,
),
"simulated": lambda: rl_utils.SimulatedBatchGymEnvWithFixedInitialFrames( # pylint: disable=g-long-lambda
**sim_env_kwargs
... |
<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_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None, batch_size=Non... |
if batch_size is None:
batch_size = env.batch_size
return {
"random": lambda: rl_utils.RandomAgent( # pylint: disable=g-long-lambda
batch_size, env.observation_space, env.action_space
),
"policy": lambda: rl_utils.PolicyAgent( # pylint: disable=g-long-lambda
batch_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 collect_frames_for_random_starts( storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit, log_every_steps=None ):
"""Collects frames fro... |
del frame_stack_size
storage_env.start_new_epoch(0)
tf.logging.info(
"Collecting %d frames for random starts.", random_starts_step_limit
)
rl_utils.run_rollouts(
stacked_env, agent, stacked_env.reset(),
step_limit=random_starts_step_limit,
many_rollouts_from_each_env=True,
log_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 make_agent_from_hparams( agent_type, base_env, stacked_env, loop_hparams, policy_hparams, planner_hparams, model_dir, policy_dir, sampling_temp, video_writers... |
def sim_env_kwargs_fn():
return rl.make_simulated_env_kwargs(
base_env, loop_hparams, batch_size=planner_hparams.batch_size,
model_dir=model_dir
)
planner_kwargs = planner_hparams.values()
planner_kwargs.pop("batch_size")
planner_kwargs.pop("rollout_agent_type")
planner_kwargs.pop("en... |
<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_eval_fn_with_agent( agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None, video_writers=(), random_starts_step_limit=None ):
"""Retur... |
def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp):
"""Eval function."""
base_env = env
env = rl_utils.BatchStackWrapper(env, loop_hparams.frame_stack_size)
agent = make_agent_from_hparams(
agent_type, base_env, env, loop_hparams, policy_hparams,
planner_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 evaluate_world_model( agent_type, loop_hparams, planner_hparams, model_dir, policy_dir, random_starts_step_limit, debug_video_path, log_every_steps ):
"""Eva... |
if debug_video_path:
debug_video_path = os.path.join(debug_video_path, "0.avi")
storage_env = rl_utils.setup_env(loop_hparams, batch_size=1, max_num_noops=0)
stacked_env = rl_utils.BatchStackWrapper(
storage_env, loop_hparams.frame_stack_size
)
policy_hparams = trainer_lib.create_hparams(loop_hpar... |
<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_open_spaces(board):
"""Given a representation of the board, returns a list of open spaces.""" |
open_spaces = []
for i in range(3):
for j in range(3):
if board[i][j] == 0:
open_spaces.append(encode_pos(i, j))
return open_spaces |
<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_reward_and_done(board):
"""Given a representation of the board, returns reward and done.""" |
# Returns (reward, done) where:
# reward: -1 means lost, +1 means win, 0 means draw or continuing.
# done: True if the game is over, i.e. someone won or it is a draw.
# Sum all rows ...
all_sums = [np.sum(board[i, :]) for i in range(3)]
# ... all columns
all_sums.extend([np.sum(board[:, i]) for i in ran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_hparams(overrides=""):
"""Hyperparameters for decoding.""" |
hp = hparam.HParams(
save_images=False,
log_results=True,
extra_length=100,
min_length_ratio=0.0,
batch_size=0,
beam_size=4,
alpha=0.6,
eos_penalty=0.0,
block_size=0,
guess_and_check_top_k=0,
guess_and_check_epsilon=-1,
insertion_parallel=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 log_decode_results(inputs, outputs, problem_name, prediction_idx, inputs_vocab, targets_vocab, targets=None, save_images=False, output_dir=None, identity_outp... |
# TODO(lukaszkaiser) refactor this into feature_encoder
is_video = "video" in problem_name or "gym" in problem_name
if is_video:
def fix_and_save_video(vid, prefix):
save_path_template = os.path.join(
output_dir,
"%s_%s_%05d_{:05d}.png" % (problem_name, prefix, prediction_idx))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_from_dataset(estimator, problem_name, hparams, decode_hp, decode_to_file=None, dataset_split=None, checkpoint_path=None):
"""Perform decoding from dat... |
tf.logging.info("Performing local inference from dataset for %s.",
str(problem_name))
# We assume that worker_id corresponds to shard number.
shard = decode_hp.shard_id if decode_hp.shards > 1 else None
# Setup output directory for any artifacts that may be written out.
output_dir = os.pat... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_filename(base_filename, problem_name, decode_hp):
"""Generates decode filename. Args: base_filename: A string, base of the decode filename. problem_n... |
if decode_hp.shards > 1:
base_filename = _add_shard_to_filename(base_filename, decode_hp)
if ("beam{beam}.alpha{alpha}.decodes".format(
beam=str(decode_hp.beam_size), alpha=str(decode_hp.alpha))
in base_filename):
return base_filename
else:
return (
"{base}.{model}.{hp}.{problem}.... |
<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_input_fn_from_generator(gen):
"""Use py_func to yield elements from the given generator.""" |
first_ex = six.next(gen)
flattened = tf.contrib.framework.nest.flatten(first_ex)
types = [t.dtype for t in flattened]
shapes = [[None] * len(t.shape) for t in flattened]
first_ex_list = [first_ex]
def py_func():
if first_ex_list:
example = first_ex_list.pop()
else:
example = six.next(g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None):
"""Interactive decoding.""" |
is_image = "image" in hparams.problem.name
is_text2class = isinstance(hparams.problem,
text_problems.Text2ClassProblem)
skip_eos_postprocess = (
is_image or is_text2class or decode_hp.skip_eos_postprocess)
def input_fn():
gen_fn = make_input_fn_from_generator(
_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary, batch_size, max_input_size, task_id=-1, has_input=True):
"""Generator to produce batche... |
tf.logging.info(" batch %d" % num_decode_batches)
for b in range(num_decode_batches):
tf.logging.info("Decoding batch %d" % b)
batch_length = 0
batch_inputs = []
for inputs in sorted_inputs[b * batch_size:(b + 1) * batch_size]:
input_ids = vocabulary.encode(inputs)
if max_input_size > 0... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _interactive_input_fn(hparams, decode_hp):
"""Generator that reads from the terminal and yields "interactive inputs". Due to temporary limitations in tf.lear... |
num_samples = decode_hp.num_samples if decode_hp.num_samples > 0 else 1
decode_length = decode_hp.extra_length
input_type = "text"
p_hparams = hparams.problem_hparams
has_input = "inputs" in p_hparams.modality
vocabulary = p_hparams.vocabulary["inputs" if has_input else "targets"]
# This should be longer... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_video(video, save_path_template):
"""Save frames of the videos into files.""" |
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires PIL library to be "
"installed: %s", e)
raise NotImplementedError("Image display and save not implemented.")
for i, frame in enumerate(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show_and_save_image(img, save_path):
"""Shows an image using matplotlib and saves it.""" |
try:
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires matplotlib to be "
"installed: %s", e)
raise NotImplementedError("Image display and save not implemented.")
plt.imshow(img)
... |
<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_language_modeling_inputs(filename, delimiter="\n", repeat=1, append_space_to_final_punctionation=True):
"""Read a file of partial texts to continue. The... |
with tf.gfile.Open(filename) as f:
text = f.read()
inputs = text.split(delimiter)
if not inputs[-1]:
inputs.pop()
inputs *= repeat
if append_space_to_final_punctionation:
inputs = [
s + " " if s and s[-1] in string.punctuation else s for s in inputs]
return inputs |
<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_sorted_inputs(filename, delimiter="\n"):
"""Returning inputs sorted according to decreasing length. This causes inputs of similar lengths to be processe... |
tf.logging.info("Getting sorted inputs")
with tf.gfile.Open(filename) as f:
text = f.read()
records = text.split(delimiter)
inputs = [record.strip() for record in records]
# Strip the last empty line.
if not inputs[-1]:
inputs.pop()
input_lens = [(i, -len(line.split())) for i, line in 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 run_postdecode_hooks(decode_hook_args, dataset_split):
"""Run hooks after decodes have run.""" |
hooks = decode_hook_args.problem.decode_hooks
if not hooks:
return
global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir)
if global_step is None:
tf.logging.info(
"Skipping decode hooks because no checkpoint yet available.")
return
tf.logging.info("Running decode hooks... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dataset_splits(self):
"""Splits of data to produce and number of output shards for each.""" |
return [{
"split": problem.DatasetSplit.TRAIN,
"shards": _TRAIN_SHARDS,
}, {
"split": problem.DatasetSplit.EVAL,
"shards": _DEV_SHARDS,
}] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_attention1d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams):
"""Image Transformer decoder with local1D spatial layers.""" |
batch_dim, length_dim, model_dim = x.shape.dims
blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length)
num_w_blocks_dim = mtf.Dimension("num_wblocks",
length_dim.size // blocks_w_dim.size)
x = mtf.reshape(
x, mtf.Shape([batch_dim, num_w_blocks_dim, blocks_w_dim, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_attention2d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams):
"""Image Transformer decoder with local2D spatial layers.""" |
batch_dim, length_dim, model_dim = x.shape.dims
blocks_h_dim = mtf.Dimension("blocksh", hparams.block_height)
blocks_w_dim = mtf.Dimension("blocksw", hparams.block_width)
num_h_blocks_dim = mtf.Dimension("num_h_blocks",
hparams.img_len // hparams.block_height)
num_w_blocks_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_attention1d_masked_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams):
"""Image Transformer decoder with local1D masked layers.""" |
print(x)
_, length_dim, model_dim = x.shape.dims
for layer in range(hparams.num_decoder_layers):
layer_name = "decoder_layer_%d" % layer
with tf.variable_scope(layer_name):
# Self attention layer
length_per_split = mtf.tensor_dim_to_size_per_split(
hparams.layout, hparams.mesh_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 create_degrees(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'):
"""Returns a list of degree vectors, one for each input an... |
if (isinstance(input_order, str) and
input_order not in ('random', 'left-to-right', 'right-to-left')):
raise ValueError('Input order is not valid.')
if hidden_order not in ('random', 'left-to-right'):
raise ValueError('Hidden order is not valid.')
degrees = []
if isinstance(input_order, str):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_masks(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'):
"""Returns a list of binary mask matrices respecting autoreg... |
degrees = create_degrees(input_dim, hidden_dims, input_order, hidden_order)
masks = []
# Create input-to-hidden and hidden-to-hidden masks.
for input_degrees, output_degrees in zip(degrees[:-1], degrees[1:]):
mask = tf.cast(input_degrees[:, np.newaxis] <= output_degrees, tf.float32)
masks.append(mask)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sinkhorn(inputs, n_iters=20):
"""Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved ma... |
vocab_size = tf.shape(inputs)[-1]
log_alpha = tf.reshape(inputs, [-1, vocab_size, vocab_size])
for _ in range(n_iters):
log_alpha -= tf.reshape(tf.reduce_logsumexp(log_alpha, axis=2),
[-1, vocab_size, 1])
log_alpha -= tf.reshape(tf.reduce_logsumexp(log_alpha, axis=1),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.