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 plot(self, tag, mpl_plt, step=None, close_plot=True):
"""Saves matplotlib plot output to summary image. Args: tag: str: label for this data mpl_plt: matplotl... |
if step is None:
step = self._step
else:
self._step = step
fig = mpl_plt.get_current_fig_manager()
img_w, img_h = fig.canvas.get_width_height()
image_buf = io.BytesIO()
mpl_plt.savefig(image_buf, format='png')
image_summary = Summary.Image(
encoded_image_string=image_buf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def audio(self, tag, audiodata, step=None, sample_rate=44100):
"""Saves audio. NB: single channel only right now. Args: tag: str: label for this data audiodata: ... |
audiodata = onp.array(audiodata)
if step is None:
step = self._step
else:
self._step = step
audiodata = onp.clip(onp.squeeze(audiodata), -1, 1)
if audiodata.ndim != 1:
raise ValueError('Audio data must be 1D.')
sample_list = (32767.0 * audiodata).astype(int).tolist()
wio =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def histogram(self, tag, values, bins, step=None):
"""Saves histogram of values. Args: tag: str: label for this data values: ndarray: will be flattened by this r... |
if step is None:
step = self._step
else:
self._step = step
values = onp.array(values)
bins = onp.array(bins)
values = onp.reshape(values, -1)
counts, limits = onp.histogram(values, bins=bins)
# boundary logic
cum_counts = onp.cumsum(onp.greater(counts, 0, dtype=onp.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 text(self, tag, textdata, step=None):
"""Saves a text summary. Args: tag: str: label for this data textdata: string, or 1D/2D list/numpy array of strings ste... |
if step is None:
step = self._step
else:
self._step = step
smd = SummaryMetadata(
plugin_data=SummaryMetadata.PluginData(plugin_name='text'))
if isinstance(textdata, (str, bytes)):
tensor = tf.make_tensor_proto(
values=[textdata.encode(encoding='utf_8')], shape=(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 import_usr_dir(usr_dir):
"""Import module at usr_dir, if provided.""" |
if not usr_dir:
return
if usr_dir == INTERNAL_USR_DIR_PACKAGE:
# The package has been installed with pip under this name for Cloud ML
# Engine so just import it.
importlib.import_module(INTERNAL_USR_DIR_PACKAGE)
return
dir_path = os.path.abspath(os.path.expanduser(usr_dir).rstrip("/"))
con... |
<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_params1():
"""A set of basic hyperparameters.""" |
return hparam.HParams(
# If the problem consists of variable-length sequences
# (see problem.batch_size_means_tokens()), then this is the number
# of tokens per batch per GPU or per TPU core. Otherwise, this is
# the number of examples per GPU or per TPU core.
batch_size=4096,
ba... |
<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_range1(ranged_hparams):
"""A basic range of hyperparameters.""" |
rhp = ranged_hparams
rhp.set_discrete("batch_size", [1024, 2048, 4096])
rhp.set_discrete("num_hidden_layers", [1, 2, 3, 4, 5, 6])
rhp.set_discrete("hidden_size", [32, 64, 128, 256, 512], scale=rhp.LOG_SCALE)
rhp.set_discrete("kernel_height", [1, 3, 5, 7])
rhp.set_discrete("kernel_width", [1, 3, 5, 7])
rh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_reset_and_type_change(self, name, orig_ctr):
"""Check if name is in orig_ctr or in one of the other type containers.""" |
# Resetting a hyperparameter
if name in orig_ctr:
tf.logging.warning("Overwriting hparam %s", name)
ctr_names = [
(self._categorical_params, "categorical"),
(self._discrete_params, "discrete"),
(self._float_params, "float"),
(self._int_params, "int"),
]
ctrs, ... |
<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_parameter_specs(self, name_prefix=""):
"""To list of dicts suitable for Cloud ML Engine hyperparameter tuning.""" |
specs = []
for name, categories, _ in self._categorical_params.values():
spec = {
"parameterName": name_prefix + name,
"type": "CATEGORICAL",
"categoricalValues": categories,
}
specs.append(spec)
for name, feasible_points, scale, _ in self._discrete_params.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 register_game(game_name, game_mode="NoFrameskip-v4"):
"""Create and register problems for the game. Args: game_name: str, one of the games in ATARI_GAMES, e.... |
if game_name not in ATARI_GAMES:
raise ValueError("Game %s not in ATARI_GAMES" % game_name)
if game_mode not in ATARI_GAME_MODES:
raise ValueError("Unknown ATARI game mode: %s." % game_mode)
camel_game_name = misc_utils.snakecase_to_camelcase(game_name) + game_mode
# Create and register the Problem
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 _decode_png(self, encoded_observation):
"""Decodes a single observation from PNG.""" |
return self._session.obj.run(
self._decoded_image_t.obj,
feed_dict={self._encoded_image_p.obj: encoded_observation}
) |
<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_observations(self, observations):
"""Encodes observations as PNG.""" |
return [
Observation(
self._session.obj.run(
self._encoded_image_t.obj,
feed_dict={self._decoded_image_p.obj: observation}
),
self._decode_png
)
for observation in observations
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def step(self, actions):
"""Makes a step in all environments. Does any preprocessing and records frames. Args: actions: Batch of actions. Returns: (obs, rewards,... |
if self._store_rollouts and \
self._rollouts_by_epoch_and_split[self.current_epoch]:
raise ValueError(
"Data for current epoch has already been loaded from disk."
)
(obs, unclipped_rewards, dones) = self._step(actions)
obs = self._preprocess_observations(obs)
(min_reward, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extra_reading_spec(self):
"""Additional data fields to store on disk and their decoders.""" |
field_names = ("frame_number", "action", "reward", "done")
data_fields = {
name: tf.FixedLenFeature([1], tf.int64) for name in field_names
}
decoders = {
name: tf.contrib.slim.tfexample_decoder.Tensor(tensor_key=name)
for name in field_names
}
return (data_fields, decode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_current_epoch(self):
"""Splits frames in the current epoch according to self.dataset_splits. Rollouts can be broken on shard boundary. This is desirab... |
num_frames = self._calc_num_frames(self._current_epoch_rollouts)
num_shards = sum(split["shards"] for split in self.dataset_splits)
shard_size = num_frames // num_shards
splits = self.dataset_splits
num_saved_frames = 0
split_index = 0
split_begin_index = 0
rollouts_by_split = collecti... |
<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_to_tf_summary_value(image, tag):
"""Converts a NumPy image to a tf.Summary.Value object. Args: image: 3-D NumPy array. tag: name for tf.Summary.Value f... |
curr_image = np.asarray(image, dtype=np.uint8)
height, width, n_channels = curr_image.shape
# If monochrome image, then reshape to [height, width]
if n_channels == 1:
curr_image = np.reshape(curr_image, [height, width])
s = io.BytesIO()
matplotlib_pyplot().imsave(s, curr_image, format="png")
img_sum ... |
<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_predictions_to_image_summaries(hook_args):
"""Optionally converts images from hooks_args to image summaries. Args: hook_args: DecodeHookArgs namedtup... |
decode_hparams = hook_args.decode_hparams
if not decode_hparams.display_decoded_images:
return []
predictions = hook_args.predictions[0]
# Display ten random inputs and outputs so that tensorboard does not hang.
all_summaries = []
rand_predictions = np.random.choice(predictions, size=10)
for ind, pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize_by_area(img, size):
"""image resize function used by quite a few image problems.""" |
return tf.to_int64(
tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) |
<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_images_as_png(images):
"""Yield images encoded as pngs.""" |
if tf.executing_eagerly():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels))
encoded_image_t = tf.image.encode_png(imag... |
<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_generator(images, labels):
"""Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x h... |
if not images:
raise ValueError("Must provide some images for the generator.")
width, height, _ = images[0].shape
for (enc_image, label) in zip(encode_images_as_png(images), labels):
yield {
"image/encoded": [enc_image],
"image/format": ["png"],
"image/class/label": [int(label)],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_shift(image, wsr=0.1, hsr=0.1):
"""Apply random horizontal and vertical shift to images. This is the default data-augmentation strategy used on CIFAR ... |
height, width, _ = common_layers.shape_list(image)
width_range, height_range = wsr*width, hsr*height
height_translations = tf.random_uniform((1,), -height_range, height_range)
width_translations = tf.random_uniform((1,), -width_range, width_range)
translations = tf.concat((height_translations, width_translat... |
<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_standard_attention_hparams(hparams):
"""Adds the hparams used by get_standardized_layers.""" |
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
# hparams used and which should have been defined outside (in
# common_hparams):
# Global flags
# hparams.mode
# hparams.hidden_size
# Pre-post processing flags
# hparams.layer_preprocess_sequence
#... |
<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_decoder_attention_loss(expected_attention_logits, actual_attentions, loss_type="kl_divergence", loss_multiplier=1.0):
"""Computes encdec attention lo... |
def combine_attentions(attention_list):
"""Combine different layer attentions and then average over layers/heads."""
# Stack all hidden layer attention tensors to get a tensor with shape
# [num_hidden_layers, batch_size, num_heads, target_length, input_length].
attentions = tf.stack(attention_list)
... |
<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_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4, start_index=0):
"""Gets a bunch of sinusoids of different frequencies. Each ch... |
position = tf.to_float(tf.range(length) + start_index)
num_timescales = channels // 2
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
tf.maximum(tf.to_float(num_timescales) - 1, 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescale... |
<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_timing_signal_1d_given_position(x, position, min_timescale=1.0, max_timescale=1.0e4):
"""Adds sinusoids of diff frequencies to a Tensor, with timing posi... |
channels = common_layers.shape_list(x)[2]
num_timescales = channels // 2
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_incre... |
<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_positional_embedding(x, max_length, name=None, positions=None):
"""Adds positional embedding. Args: x: Tensor with shape [batch, length, depth]. max_leng... |
with tf.name_scope("add_positional_embedding"):
_, length, depth = common_layers.shape_list(x)
var = tf.cast(tf.get_variable(name, [max_length, depth]), x.dtype)
if positions is None:
pad_length = tf.maximum(0, length - max_length)
sliced = tf.cond(
tf.less(length, max_length),
... |
<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_positional_embedding_nd(x, max_length, name=None):
"""Adds n-dimensional positional embedding. The embeddings add to all positional dimensions of the ten... |
with tf.name_scope("add_positional_embedding_nd"):
x_shape = common_layers.shape_list(x)
num_dims = len(x_shape) - 2
depth = x_shape[-1]
base_shape = [1] * (num_dims + 1) + [depth]
base_start = [0] * (num_dims + 2)
base_size = [-1] + [1] * num_dims + [depth]
for i in range(num_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 make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None):
"""Gets edge vectors for the edge types in the adjacency matrix. Args: adjacency_matri... |
with tf.variable_scope(name, default_name="edge_vectors"):
att_adj_vectors_shape = [num_edge_types, depth]
adjacency_matrix_shape = common_layers.shape_list(adjacency_matrix)
adj_vectors = (
tf.get_variable(
"adj_vectors",
att_adj_vectors_shape,
initializer=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 padding_to_length(padding):
"""Calculate the length of mask based on padding. Args: Returns: """ |
non_padding = 1.0 - padding
return tf.to_int32(tf.reduce_sum(non_padding, axis=-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 attention_bias_prepend_inputs_full_attention(padding):
"""Create a bias tensor for prepend_mode="prepend_inputs_full_attention". See prepend_inputs in common... |
# Everything past the first padding position is part of the target.
# This Tensor has zeros for the source portion and separator,
# and ones for the target portion.
in_target = tf.cumsum(padding, axis=1, exclusive=True)
# The position within the target, or 0 if part of the source.
target_pos = tf.cumsum(in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attention_bias_proximal(length):
"""Bias for self-attention to encourage attention to close positions. Args: length: an integer scalar. Returns: a Tensor wit... |
r = tf.to_float(tf.range(length))
diff = tf.expand_dims(r, 0) - tf.expand_dims(r, 1)
return tf.expand_dims(tf.expand_dims(-tf.log1p(tf.abs(diff)), 0), 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 attention_bias_batch(batch_coordinates_q, batch_coordinates_k=None, condition_fn=None):
"""Generate a mask to prevent the batch to attend to each others. Arg... |
if batch_coordinates_k is None:
batch_coordinates_k = batch_coordinates_q
# Convert to float first because of b/25387198.
def to_float(bc):
bc = tf.squeeze(bc, 1)
bc = tf.to_float(bc)
return bc
# Broadcast to create [length_q, length_k] mask.
bc_v = tf.expand_dims(to_float(batch_coordinates... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_last_dimension(x, n):
"""Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Args: n: an integer. Retu... |
x_shape = common_layers.shape_list(x)
m = x_shape[-1]
if isinstance(m, int) and isinstance(n, int):
assert m % n == 0
return tf.reshape(x, x_shape[:-1] + [n, m // 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 combine_last_two_dimensions(x):
"""Reshape x so that the last two dimension become one. Args: Returns: """ |
x_shape = common_layers.shape_list(x)
a, b = x_shape[-2:]
return tf.reshape(x, x_shape[:-2] + [a * 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 combine_first_two_dimensions(x):
"""Reshape x so that the first two dimension become one. Args: Returns: """ |
ret = tf.reshape(x, tf.concat([[-1], common_layers.shape_list(x)[2:]], 0))
old_shape = x.get_shape().dims
a, b = old_shape[:2]
new_shape = [a * b if a and b else None] + old_shape[2:]
ret.set_shape(new_shape)
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 attention_image_summary(attn, image_shapes=None):
"""Compute color image summary. Args: attn: a Tensor with shape [batch, num_heads, query_length, memory_len... |
attn = tf.cast(attn, tf.float32)
num_heads = common_layers.shape_list(attn)[1]
# [batch, query_length, memory_length, num_heads]
image = tf.transpose(attn, [0, 2, 3, 1])
image = tf.pow(image, 0.2) # for high-dynamic-range
# Each head will correspond to one of RGB.
# pad the heads to be a multiple of 3
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def harden_attention_weights(weights, hard_attention_k):
"""Make attention weights non-0 only on the top-hard_attention_k ones.""" |
# Subtract the top-kth weight and zero-out all lower ones.
# Note that currently in case of numerical ties it will retain more
# than k elements. In the future, we may want to avoid this.
weights -= common_layers.top_kth_iterative(weights, hard_attention_k)
weights = tf.nn.relu(weights)
# Re-normalize 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 _generate_relative_positions_matrix(length_q, length_k, max_relative_position, cache=False):
"""Generates matrix of relative positions between inputs.""" |
if not cache:
if length_q == length_k:
range_vec_q = range_vec_k = tf.range(length_q)
else:
range_vec_k = tf.range(length_k)
range_vec_q = range_vec_k[-length_q:]
distance_mat = range_vec_k[None, :] - range_vec_q[:, None]
else:
distance_mat = tf.expand_dims(tf.range(-length_k+1, 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 _relative_attention_inner(x, y, z, transpose):
"""Relative position-aware dot-product attention inner calculation. This batches matrix multiply calculations ... |
batch_size = tf.shape(x)[0]
heads = x.get_shape().as_list()[1]
length = tf.shape(x)[2]
# xy_matmul is [batch_size, heads, length or 1, length or depth]
xy_matmul = tf.matmul(x, y, transpose_b=transpose)
# x_t is [length or 1, batch_size, heads, length or depth]
x_t = tf.transpose(x, [2, 0, 1, 3])
# 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 _relative_position_to_absolute_position_masked(x):
"""Helper to dot_product_self_attention_relative_v2. Rearrange an attention logits or weights Tensor. The ... |
batch, heads, length, _ = common_layers.shape_list(x)
x = tf.pad(x, [[0, 0], [0, 0], [0, 0], [1, 0]])
x = tf.reshape(x, [batch, heads, 1 + length, length])
x = tf.slice(x, [0, 0, 1, 0], [-1, -1, -1, -1])
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 _absolute_position_to_relative_position_unmasked(x):
"""Helper function for dot_product_unmasked_self_attention_relative_v2. Rearrange an attention logits or... |
batch, heads, length, _ = common_layers.shape_list(x)
# padd along column
x = tf.pad(x, [[0, 0], [0, 0], [0, 0], [0, length-1]])
x_flat = tf.reshape(x, [batch, heads, length**2 + length*(length -1)])
# add 0's in the beginning that will skew the elements after reshape
x_flat = tf.pad(x_flat, [[0, 0], [0, 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 get_relative_embeddings_left_right(max_relative_position, length, depth, num_heads, heads_share_relative_embedding, name):
"""Instantiate or retrieve relativ... |
initializer_stddev = depth**-0.5
max_relative_position_unmasked = 2 * max_relative_position - 1
if heads_share_relative_embedding:
embedding_shape = (max_relative_position_unmasked, depth)
else:
embedding_shape = (num_heads, max_relative_position_unmasked, depth)
relative_embeddings = tf.get_variable... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _matmul_with_relative_keys_2d(x, y, heads_share_relative_embedding):
"""Helper function for dot_product_unmasked_self_attention_relative_2d.""" |
if heads_share_relative_embedding:
ret = tf.einsum("bhxyd,md->bhxym", x, y)
else:
ret = tf.einsum("bhxyd,hmd->bhxym", x, y)
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 _get_left_right_blocks(x):
"""Helper function. Assumes that memory_flange is half of query sizes. This function splits the tensor of width 'n' into two halve... |
(_, x_num_outer_h_blocks, x_num_outer_w_blocks, x_memory_flange_h,
x_memory_flange_w, depth) = common_layers.shape_list(x)
x_left_right_blocks = tf.slice(x,
[0, 1, 0, 0, 0, 0],
[-1, x_num_outer_h_blocks-2, -1, -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_2d_local_memory(x, query_shape, memory_flange):
"""Stitches together the local 2d memory blocks. Args: x: a [batch, height, width, depth tensor] query_sh... |
(_, height, width, depth_x) = common_layers.shape_list(x)
x_center_blocks = _extract_blocks(x, query_shape[0], query_shape[1])
# add extra padding to x so that we can extract the memory region
# around the center
paddings = [[0, 0], [memory_flange[0], memory_flange[0]],
[memory_flange[1], memor... |
<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_2d_local_memory_v2(x, query_shape, memory_flange):
"""Gathering memory blocks around query blocks. flange is half of query . Only works if memory flanges... |
(_, height, width, depth_x) = common_layers.shape_list(x)
# add extra padding to x so that we can extract the memory region
# around the center
paddings = [[0, 0], [memory_flange[0], memory_flange[0]],
[memory_flange[1], memory_flange[1]], [0, 0]]
padded_x = tf.pad(x, paddings)
padded_x.set_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 dot_product_unmasked_attention_local_2d_tpu_simple( x, bias, total_key_depth, total_value_depth, num_heads, query_shape=(8, 8), dropout_rate=0.0, image_shapes... |
# This calculation only works for self attention.
# q, k and v must therefore have the same shape.
orig_x_shape = common_layers.shape_list(x)
# Pad query, key, value to ensure multiple of corresponding lengths if
# necessary
is_padded = False
if (orig_x_shape[1]%query_shape[0]) != 0 or (
orig_x_sha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def masked_within_block_local_attention_1d(q, k, v, block_length=64, name=None):
"""Attention to the source and a neighborhood to the left within a block. The se... |
with tf.variable_scope(
name, default_name="within_local_attention_1d", values=[q, k, v]):
batch, heads, length, depth_k = common_layers.shape_list(q)
depth_v = common_layers.shape_list(v)[-1]
if isinstance(block_length, tf.Tensor):
const = tf.contrib.util.constant_value(block_length)
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _relative_position_to_absolute_position_unmasked(x):
"""Converts tensor from relative to aboslute indexing for local attention. Args: x: a Tensor of shape [b... |
x_shape = common_layers.shape_list(x)
batch = x_shape[0]
heads = x_shape[1]
length = x_shape[2]
# Concat columns of pad to shift from relative to absolute indexing.
col_pad = tf.zeros((batch, heads, length, 1))
x = tf.concat([x, col_pad], axis=3)
# Concat extra elements so to add up to shape (len+1, 2... |
<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_local_block(x, depth, batch, heads, num_blocks, block_length):
"""Helper function to create a local version of the keys or values for 1d.""" |
prev_block = tf.slice(x, [0, 0, 0, 0, 0],
[-1, -1, num_blocks - 1, -1, -1])
cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1])
local_block = tf.concat([prev_block, cur_block], 3)
return tf.reshape(local_block,
[batch, heads, num_blocks - 1, block_length *... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reshape_by_blocks(x, x_shape, memory_block_size):
"""Reshapes input by splitting its length over blocks of memory_block_size. Args: x: a Tensor with shape [b... |
x = tf.reshape(x, [
x_shape[0], x_shape[1], x_shape[2] // memory_block_size,
memory_block_size, x_shape[3]
])
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 gather_dilated_memory_blocks(x, num_memory_blocks, gap_size, query_block_size, memory_block_size, gather_indices, direction="left"):
"""Gathers blocks with g... |
gathered_blocks = []
# gathering memory blocks
for block_id in range(num_memory_blocks):
block_end_index = -(query_block_size + gap_size *
(block_id + 1) + memory_block_size * block_id)
block_start_index = (
(memory_block_size + gap_size) * (num_memory_blocks - (block_id +... |
<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_to_multiple_2d(x, block_shape):
"""Making sure x is a multiple of shape. Args: x: a [batch, heads, h, w, depth] or [batch, h, w, depth] tensor block_shap... |
old_shape = x.get_shape().dims
last = old_shape[-1]
if len(old_shape) == 4:
height_padding = -common_layers.shape_list(x)[1] % block_shape[0]
width_padding = -common_layers.shape_list(x)[2] % block_shape[1]
paddings = [[0, 0], [0, height_padding], [0, width_padding], [0, 0]]
elif len(old_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 reshape_range(tensor, i, j, shape):
"""Reshapes a tensor between dimensions i and j.""" |
t_shape = common_layers.shape_list(tensor)
target_shape = t_shape[:i] + shape + t_shape[j:]
return tf.reshape(tensor, target_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 gather_blocks_2d(x, indices):
"""Gathers flattened blocks from x.""" |
x_shape = common_layers.shape_list(x)
x = reshape_range(x, 2, 4, [tf.reduce_prod(x_shape[2:4])])
# [length, batch, heads, dim]
x_t = tf.transpose(x, [2, 0, 1, 3])
x_new = tf.gather(x_t, indices)
# returns [batch, heads, num_blocks, block_length ** 2, dim]
return tf.transpose(x_new, [2, 3, 0, 1, 4]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scatter_blocks_2d(x, indices, shape):
"""scatters blocks from x into shape with indices.""" |
x_shape = common_layers.shape_list(x)
# [length, batch, heads, dim]
x_t = tf.transpose(
tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3])
x_t_shape = common_layers.shape_list(x_t)
indices = tf.reshape(indices, [-1, 1])
scattered_x = tf.scatter_nd(indices, x_t, x_t_shape)
scatt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gather_indices_2d(x, block_shape, block_stride):
"""Getting gather indices.""" |
# making an identity matrix kernel
kernel = tf.eye(block_shape[0] * block_shape[1])
kernel = reshape_range(kernel, 0, 1, [block_shape[0], block_shape[1], 1])
# making indices [1, h, w, 1] to appy convs
x_shape = common_layers.shape_list(x)
indices = tf.range(x_shape[2] * x_shape[3])
indices = tf.reshape(... |
<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_2d_block_raster_mask(query_shape, memory_flange):
"""Creates a mask for 2d block raster scan. The query mask can look to the left, top left, top, and to... |
# mask inside the query block
query_triangle = common_layers.ones_matrix_band_part(
np.prod(query_shape), np.prod(query_shape), -1, 0)
split_query_masks = tf.split(query_triangle, query_shape[0], axis=1)
# adding mask for left and right
mask_pieces = [
tf.concat( # pylint: disable=g-complex-comp... |
<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_memory_region(x, query_block_shape, memory_flange, q_indices):
"""Get the memory regions that surround a 2d query. The memory regions will be the left an... |
# Padding x to be multiple of query_shape and then
# extracting the memory blocks from the same regions as the query blocks
x_query_padded = pad_to_multiple_2d(x, query_block_shape)
x_center = gather_blocks_2d(x_query_padded, q_indices)
# Then padding the flange region
paddings = [[0, 0], [0, 0], [memory_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 get_shifted_center_blocks(x, indices):
"""Get right shifted blocks for masked local attention 2d. Args: x: A tensor with shape [batch, heads, height, width, ... |
center_x = gather_blocks_2d(x, indices)
# Shift right along the length dimension
def shift_right_2d_blocks(x):
"""Shift the second to last dimension of x right by one."""
shifted_targets = (
tf.pad(x, [[0, 0], [0, 0], [0, 0], [1, 0], [0, 0]])[:, :, :, :-1, :])
return shifted_targets
x_shi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def right_shift_blockwise(x, query_shape, name=None):
"""Right shifts once in every block. Args: x: a tensor of shape [batch, height, width, depth] query_shape: ... |
with tf.variable_scope(
name, default_name="right_shift_blockwise", values=[x]):
x_list_shape = x.get_shape().as_list()
x_shape = common_layers.shape_list(x)
# Add a dummy dimension for heads.
x = tf.expand_dims(x, axis=1)
x = pad_to_multiple_2d(x, query_shape)
padded_x_shape = common_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 compute_qkv(query_antecedent, memory_antecedent, total_key_depth, total_value_depth, q_filter_width=1, kv_filter_width=1, q_padding="VALID", kv_padding="VALID... |
if memory_antecedent is None:
memory_antecedent = query_antecedent
q = compute_attention_component(
query_antecedent,
total_key_depth,
q_filter_width,
q_padding,
"q",
vars_3d_num_heads=vars_3d_num_heads,
layer_collection=layer_collection)
k = compute_attention_compon... |
<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_self_attention_layer(x, filter_depth, output_depth, num_parts, dropout_rate, share_kv=False, name=None):
"""Self-attention feedforward layer. We use self... |
with tf.variable_scope(
name, default_name="feedforward_self_attention", values=[x]):
x_shape = common_layers.shape_list(x)
part_depth = filter_depth // num_parts
if not share_kv:
combined = common_layers.dense(
x, filter_depth * 3, use_bias=False, name="qkv_transform")
combin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameter_attention(x, total_key_depth, total_value_depth, output_depth, memory_rows, num_heads, dropout_rate, name=None):
"""Attention over parameters. We u... |
with tf.variable_scope(name, default_name="parameter_attention", values=[x]):
head_size_k = total_key_depth // num_heads
head_size_v = total_value_depth // num_heads
var_shape_k = [num_heads, memory_rows, head_size_k]
var_shape_v = [num_heads, memory_rows, head_size_v]
k = tf.get_variable(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coordinate_tensor(shape, axis):
"""Return a tensor with given shape containing coordinate along given axis. Args: shape: a Tensor representing the shape of t... |
if axis < 0:
axis = tf.size(shape) + axis # Convert to positive for the one_hot indice
r = tf.range(shape[axis])
r_shape = tf.one_hot(
axis, tf.size(shape), on_value=-1, off_value=1, dtype=tf.int32)
return tf.zeros(shape, dtype=tf.int32) + tf.reshape(r, r_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 self_attention_expert(x, batch_coordinate, mask_right=True, split_batch=False, attention_num_head=1, attention_kq_size=None, attention_v_size=None):
"""Imple... |
depth = x.get_shape().as_list()[-1]
length = common_layers.shape_list(batch_coordinate)[0]
# Print a warning message if one of the expert isn't used (useful at
# inference where summaries aren't used and the gating function don't add
# noise)
global _expert_count # Hack to make each expert have a unique... |
<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_expert_attention(x, k, loss_coef, attention_num_experts, train=True, batch_coordinate=None, **kwargs):
"""Attention using a mixture of experts. Positio... |
if batch_coordinate is None:
batch_coordinate = tf.expand_dims(
coordinate_tensor(common_layers.shape_list(x)[:-1], axis=0), axis=-1)
with tf.variable_scope("local_expert_attention"):
additional_dispatch_params = {"batch_coordinate": batch_coordinate}
return expert_utils.local_moe(
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 expert_dot_product(q, k, v, info_q, info_k):
"""Perform dot product on a subset of the sequence. Can add a mask to the attention to prevent sequences to atte... |
length_q = common_layers.shape_list(q)[0]
length_k = common_layers.shape_list(k)[0]
depth_v = v.get_shape().as_list()[-1]
# Create the mask
bias = attention_bias_coordinates(info_q.coordinates, info_k.coordinates)
if info_k.order is not None:
bias += attention_bias_future(info_q.order, info_k.order)
... |
<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_fn_switch(fn, elems, use_map_fn=True, **kwargs):
"""Construct the graph with either tf.map_fn or a python for loop. This function is mainly for for bench... |
if use_map_fn:
return tf.map_fn(fn, elems, **kwargs)
elems_unpacked = (tf.unstack(e) for e in elems)
out_unpacked = [fn(e) for e in zip(*elems_unpacked)]
out = tf.stack(out_unpacked)
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deconv_elems_1d(x, factor, out_depth=None):
"""Increase the length and change the dimensionality. Expand/project each positions of dim depth of the input int... |
out_depth = out_depth or x.get_shape().as_list()[-1]
x = tf.expand_dims(x, 1) # [batch_size, 1, length, depth]
x = layers().Conv2DTranspose(
filters=out_depth,
kernel_size=(1, factor),
strides=(1, factor),
padding="valid",
data_format="channels_last",
)(x) # [batch_size, 1, leng... |
<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_elems_1d(x, factor, out_depth=None):
"""Decrease the length and change the dimensionality. Merge/restore/compress factors positions of dim depth of the ... |
out_depth = out_depth or x.get_shape().as_list()[-1]
# with tf.control_dependencies( # Dynamic assertion
# [tf.assert_equal(tf.shape(x)[1] % factor, 0)]):
x = tf.expand_dims(x, 1) # [batch_size, 1, length, depth]
x = layers().Conv2D(
filters=out_depth,
kernel_size=(1, factor),
strides... |
<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_reduction_attention(x, block_length, multihead_params):
"""Reduce the length dimension using self attention. Args: x (tf.Tensor):
float32 of shape [ba... |
@expert_utils.add_name_scope()
def dot_product_self_local_attention_flattened(q, k, v):
"""Strided block local self-attention.
No overlap between the blocks.
Args:
q (tf.Tensor): shape [batch, heads, length, depth_k]
k (tf.Tensor): shape [batch, heads, length, depth_k]
v (tf.Tensor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def multihead_self_attention_reduced( x, memory_antecedent=None, bias=None, factor=None, multihead_params=None, nonlinearity="none", reduction_type="conv", add_ma... |
if not factor or not multihead_params:
raise ValueError("factor and multihead_params should be set")
if memory_antecedent is not None:
raise NotImplementedError(
"multihead_self_attention_reduced only works with self-attention")
depth = x.get_shape().as_list()[-1]
# Could try to have some ove... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scaled_dot_product_attention_simple(q, k, v, bias, name=None):
"""Scaled dot-product attention. One head. One spatial dimension. Args: q: a Tensor with shape... |
with tf.variable_scope(
name, default_name="scaled_dot_product_attention_simple"):
scalar = tf.rsqrt(tf.to_float(common_layers.shape_list(q)[2]))
logits = tf.matmul(q * scalar, k, transpose_b=True)
if bias is not None:
logits += bias
weights = tf.nn.softmax(logits, name="attention_weights... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _idx_to_bits(self, i):
"""Convert an group index to its bit representation.""" |
bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0
return [-1.0 if b == "0" else 1.0 for b in bits] |
<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_gates(self, x):
"""Return the bucket id of the given tensor. Args: x (tf.Tensor):
float32 of shape [length, depth] Returns: tf.Tensor: One-hot vector in... |
# The balance loss don't propagate to the rest of the network
x = tf.stop_gradient(x)
# [length, depth] * [depth, nb_vectors * replicat]
x = tf.matmul(x, self.t_vectors)
# [length, nb_vector * replicat]
x = tf.sign(x) # Get on which side of the hyperplane the keys are.
# x = tf.reshape(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 van_image_enc_2d(x, first_depth, reuse=False, hparams=None):
"""The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.... |
with tf.variable_scope('van_image_enc', reuse=reuse):
enc_history = [x]
enc = tf.layers.conv2d(
x, first_depth, 3, padding='same', activation=tf.nn.relu, strides=1)
enc = tf.contrib.layers.layer_norm(enc)
enc = tf.layers.conv2d(
enc, first_depth, 3, padding='same', activation=tf.nn.r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def van_enc_2d(x, first_depth, reuse=False):
"""The higher level structure encoder for the VAN. The high level structure is a vector instead of an image. Args: x... |
with tf.variable_scope('van_enc', reuse=reuse):
a = 4 # depends on the inputs size
b = 4
# a, b = 4,4
enc = tf.nn.relu(x)
enc = tf.layers.dense(enc, first_depth * a * b, tf.nn.relu)
enc = tf.contrib.layers.layer_norm(enc)
enc = tf.reshape(enc, [-1, a, b, first_depth])
enc = tf.laye... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None):
"""The VAN decoder. Args: x: The analogy information to decode. skip_connections: T... |
with tf.variable_scope('van_dec'):
dec = tf.layers.conv2d_transpose(
x, first_depth * 4, 3, padding='same', activation=tf.nn.relu, strides=2)
dec = tf.nn.dropout(dec, hparams.van_keep_prob)
dec = tf.contrib.layers.layer_norm(dec)
dec = tf.layers.conv2d_transpose(
dec,
first_de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analogy_computation_2d(f_first_enc, f_first_frame, f_current_enc, first_depth):
"""Implements the deep analogy computation.""" |
with tf.variable_scope('analogy_computation'):
frame_enc_diff = f_first_frame - f_first_enc
frame_enc_diff_enc = tf.layers.conv2d(
frame_enc_diff,
first_depth * 4,
3,
padding='same',
activation=tf.nn.relu,
strides=1)
f_current_enc_enc = tf.layers.conv2d(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def van(first_enc, first_frame, current_enc, gt_image, reuse=False, scope_prefix='', hparams=None):
"""Implements a VAN. Args: first_enc: The first encoding. fir... |
with tf.variable_scope(scope_prefix + 'van', reuse=reuse):
output_shape = first_frame.get_shape().as_list()
output_shape[0] = -1
first_depth = 64
f_first_enc, _ = van_enc_2d(first_enc, first_depth)
f_first_frame, image_enc_history = van_image_enc_2d(
first_frame, first_depth, hparams=hp... |
<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_vgg(x, enc_final_size, reuse=False, scope_prefix='', hparams=None, is_training=True):
"""VGG network to use as encoder without the top few layers. Ca... |
with tf.variable_scope(scope_prefix + 'encoder', reuse=reuse):
# Preprocess input
x *= 256
x = x - COLOR_NORMALIZATION_VECTOR
with arg_scope(vgg.vgg_arg_scope()):
# Padding because vgg_16 accepts images of size at least VGG_IMAGE_SIZE.
x = tf.pad(x, [[0, 0], [0, VGG_IMAGE_SIZE - IMG_WID... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predictor(enc_flat, action, lstm_states, pred_depth, reuse=False, scope_prefix='', hparams=None):
"""LSTM predictor network.""" |
with tf.variable_scope(scope_prefix + 'predict', reuse=reuse):
enc_final_size = enc_flat.get_shape().as_list()[1]
action_size = action.get_shape().as_list()[1]
initial_size = (enc_final_size + action_size)
batch_size = tf.shape(enc_flat)[0]
init_stddev = 1e-2
pre_pred = tf.concat([enc_fla... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct_model(images, actions=None, context_frames=2, hparams=None, is_training=True):
"""Constructs the tensorflow graph of the hierarchical model.""" |
pred_depth = 20
enc_out_all, pred_out_all, van_out_all, van_on_enc_all = [], [], [], []
lstm_states = [None] * (pred_depth + 2)
enc_out = encoder_vgg(
images[0], hparams.enc_size, False, scope_prefix='timestep/',
hparams=hparams, is_training=is_training)
enc_out = tf.identity(enc_out, 'enc_ou... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def peak_signal_to_noise_ratio(true, pred):
"""Image quality metric based on maximal signal power vs. power of the noise. Args: true: the ground truth image. pre... |
return 10.0 * tf.log(1.0 / mean_squared_error(true, pred)) / tf.log(10.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 mean_squared_error(true, pred):
"""L2 distance between tensors true and pred. Args: true: the ground truth image. pred: the predicted image. Returns: mean sq... |
result = tf.reduce_sum(
tf.squared_difference(true, pred)) / tf.to_float(tf.size(pred))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def l1_error(true, pred):
"""L1 distance between tensors true and pred.""" |
return tf.reduce_sum(tf.abs(true - pred)) / tf.to_float(tf.size(pred)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_loss_psnr(gen_images, images, name, hparams=None, use_l1_loss=False):
"""Calculates loss and psnr for predictions over multiple timesteps.""" |
del hparams
with tf.name_scope(name):
loss, error, psnr_all = 0.0, 0.0, 0.0
for _, x, gx in zip(range(len(gen_images)), images, gen_images):
recon_cost = mean_squared_error(x, gx)
if use_l1_loss:
recon_cost = l1_error(x, gx)
error_i = l1_error(x, gx)
psnr_i = peak_signal_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 next_frame_sv2p():
"""SV2P model hparams.""" |
hparams = basic_stochastic.next_frame_basic_stochastic()
hparams.optimizer = "true_adam"
hparams.learning_rate_schedule = "constant"
hparams.learning_rate_constant = 1e-3
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 3
hparams.batch_size = 16
hparams.bottom = {
"inputs": mo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next_frame_sv2p_discrete():
"""SV2P discrete model hparams.""" |
hparams = next_frame_sv2p()
hparams.action_injection = "multiplicative"
hparams.small_mode = True
hparams.add_hparam("bottleneck_bits", 128)
hparams.add_hparam("bottleneck_noise", 0.02)
hparams.add_hparam("discrete_warmup_steps", 40000)
hparams.add_hparam("full_latent_tower", False)
hparams.add_hparam(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next_frame_sv2p_atari():
"""SV2P model for atari.""" |
hparams = next_frame_sv2p()
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.action_injection = "multiplicative"
hparams.num_iterations_1st_stage = 12000
hparams.num_iterations_2nd_stage = 12000
hparams.anneal_end = 40000
hparams.latent_loss_multiplier_schedule = "noisy_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 next_frame_sv2p_atari_softmax():
"""SV2P model for atari with softmax.""" |
hparams = next_frame_sv2p_atari()
hparams.bottom = {}
hparams.loss = {}
hparams.top = {}
hparams.internal_loss = True
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 next_frame_sv2p_tiny():
"""Tiny SV2P model.""" |
hparams = next_frame_sv2p_atari_softmax()
hparams.batch_size = 2
hparams.tiny_mode = True
hparams.num_masks = 1
hparams.video_modality_loss_cutoff = 0.4
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
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 next_frame_sv2p_cutoff():
"""SV2P model with additional cutoff in L2 loss for environments like pong.""" |
hparams = next_frame_sv2p()
hparams.video_modality_loss_cutoff = 0.4
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 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 _get_mscoco(directory):
"""Download and extract MSCOCO datasets to directory unless it is there.""" |
for url in _MSCOCO_URLS:
filename = os.path.basename(url)
download_url = os.path.join(_MSCOCO_ROOT_URL, url)
path = generator_utils.maybe_download(directory, filename, download_url)
unzip_dir = os.path.join(directory, filename.strip(".zip"))
if not tf.gfile.Exists(unzip_dir):
zipfile.ZipFil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mscoco_generator(data_dir, tmp_dir, training, how_many, start_from=0, eos_list=None, vocab_filename=None):
"""Image generator for MSCOCO captioning problem w... |
eos_list = [1] if eos_list is None else eos_list
def get_vocab():
"""Get vocab for caption text encoder."""
if data_dir is not None and vocab_filename is not None:
vocab_filepath = os.path.join(data_dir, vocab_filename)
if tf.gfile.Exists(vocab_filepath):
tf.logging.info("Found vocab 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 flags_as_args():
"""Convert FLAGS to list of args suitable for passing on cmd line.""" |
if hasattr(FLAGS, "flag_values_dict"):
args_dict = FLAGS.flag_values_dict()
else:
args_dict = dict(FLAGS.__dict__["__flags"])
del args_dict["cloud_mlengine"]
# Configured later
del args_dict["t2t_usr_dir"]
args_dict.pop("h", None)
args_dict.pop("helpfull", None)
args_dict.pop("helpshort", None)... |
<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_default_master_type(num_gpus=1):
"""Returns master_type for trainingInput.""" |
gpus_to_master_map = {
0: "standard",
1: "standard_p100",
4: "complex_model_m_p100",
8: "complex_model_l_gpu",
}
if num_gpus not in gpus_to_master_map:
raise ValueError("Num gpus must be in %s" %
str(sorted(list(gpus_to_master_map.keys()))))
return gpus_to_maste... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_job():
"""Construct jobSpec for ML Engine job.""" |
# See documentation:
# https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#traininginput
training_input = {
"pythonModule": "tensor2tensor.bin.t2t_trainer",
"args": flags_as_args(),
"region": text_encoder.native_to_unicode(default_region()),
"runtimeVersion": RUNTIME_VERSIO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def launch_job(job_spec):
"""Launch job on ML Engine.""" |
project_id = "projects/{}".format(
text_encoder.native_to_unicode(default_project()))
credentials = GoogleCredentials.get_application_default()
cloudml = discovery.build("ml", "v1", credentials=credentials,
cache_discovery=False)
request = cloudml.projects().jobs().create(body... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.