text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Finer segmentation for search engines.
<END_TASK>
<USER_TASK:>
Description:
def cut_for_search(self, sentence, HMM=True):
"""
Finer segmentation for search engines.
""" |
words = self.cut(sentence, HMM=HMM)
for w in words:
if len(w) > 2:
for i in xrange(len(w) - 1):
gram2 = w[i:i + 2]
if self.FREQ.get(gram2):
yield gram2
if len(w) > 3:
for i in xrange(len(w) - 2):
gram3 = w[i:i + 3]
if self.FREQ.get(gram3):
yield gram3
yield w |
<SYSTEM_TASK:>
Add a word to dictionary.
<END_TASK>
<USER_TASK:>
Description:
def add_word(self, word, freq=None, tag=None):
"""
Add a word to dictionary.
freq and tag can be omitted, freq defaults to be a calculated value
that ensures the word can be cut out.
""" |
self.check_initialized()
word = strdecode(word)
freq = int(freq) if freq is not None else self.suggest_freq(word, False)
self.FREQ[word] = freq
self.total += freq
if tag:
self.user_word_tag_tab[word] = tag
for ch in xrange(len(word)):
wfrag = word[:ch + 1]
if wfrag not in self.FREQ:
self.FREQ[wfrag] = 0
if freq == 0:
finalseg.add_force_split(word) |
<SYSTEM_TASK:>
Suggest word frequency to force the characters in a word to be
<END_TASK>
<USER_TASK:>
Description:
def suggest_freq(self, segment, tune=False):
"""
Suggest word frequency to force the characters in a word to be
joined or splitted.
Parameter:
- segment : The segments that the word is expected to be cut into,
If the word should be treated as a whole, use a str.
- tune : If True, tune the word frequency.
Note that HMM may affect the final result. If the result doesn't change,
set HMM=False.
""" |
self.check_initialized()
ftotal = float(self.total)
freq = 1
if isinstance(segment, string_types):
word = segment
for seg in self.cut(word, HMM=False):
freq *= self.FREQ.get(seg, 1) / ftotal
freq = max(int(freq * self.total) + 1, self.FREQ.get(word, 1))
else:
segment = tuple(map(strdecode, segment))
word = ''.join(segment)
for seg in segment:
freq *= self.FREQ.get(seg, 1) / ftotal
freq = min(int(freq * self.total), self.FREQ.get(word, 0))
if tune:
add_word(word, freq)
return freq |
<SYSTEM_TASK:>
Obtain a list of image paths corresponding to training or eval case.
<END_TASK>
<USER_TASK:>
Description:
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95):
"""Obtain a list of image paths corresponding to training or eval case.
Args:
tmp_dir: str, the root path to which raw images were written, at the
top level having meta/ and raw/ subdirs.
case: bool, whether obtaining file paths for training (true) or eval
(false).
training_fraction: float, the fraction of the sub-image path list to
consider as the basis for training examples.
Returns:
list: A list of file paths.
Raises:
ValueError: if images not found in tmp_dir, or if training_fraction would
leave no examples for eval.
""" |
paths = tf.gfile.Glob("%s/*.jpg" % tmp_dir)
if not paths:
raise ValueError("Search of tmp_dir (%s) " % tmp_dir,
"for subimage paths yielded an empty list, ",
"can't proceed with returning training/eval split.")
split_index = int(math.floor(len(paths)*training_fraction))
if split_index >= len(paths):
raise ValueError("For a path list of size %s "
"and a training_fraction of %s "
"the resulting split_index of the paths list, "
"%s, would leave no elements for the eval "
"condition." % (len(paths),
training_fraction,
split_index))
if case:
return paths[:split_index]
else:
return paths[split_index:] |
<SYSTEM_TASK:>
Download a set of images from api.brain-map.org to `target_dir`.
<END_TASK>
<USER_TASK:>
Description:
def maybe_download_image_dataset(image_ids, target_dir):
"""Download a set of images from api.brain-map.org to `target_dir`.
Args:
image_ids: list, a list of image ids.
target_dir: str, a directory to which to download the images.
""" |
tf.gfile.MakeDirs(target_dir)
num_images = len(image_ids)
for i, image_id in enumerate(image_ids):
destination = os.path.join(target_dir, "%s.jpg" % i)
tmp_destination = "%s.temp" % destination
source_url = ("http://api.brain-map.org/api/v2/"
"section_image_download/%s" % image_id)
if tf.gfile.Exists(destination):
tf.logging.info("Image with ID already present, "
"skipping download (%s of %s)." % (
i+1, num_images
))
continue
tf.logging.info("Downloading image with id %s (%s of %s)" % (
image_id, i+1, num_images
))
response = requests.get(source_url, stream=True)
response.raise_for_status()
with tf.gfile.Open(tmp_destination, "w") as f:
for block in response.iter_content(1024):
f.write(block)
tf.gfile.Rename(tmp_destination, destination) |
<SYSTEM_TASK:>
Create a numpy array with specified shape and masked fraction.
<END_TASK>
<USER_TASK:>
Description:
def random_square_mask(shape, fraction):
"""Create a numpy array with specified shape and masked fraction.
Args:
shape: tuple, shape of the mask to create.
fraction: float, fraction of the mask area to populate with `mask_scalar`.
Returns:
numpy.array: A numpy array storing the mask.
""" |
mask = np.ones(shape)
patch_area = shape[0]*shape[1]*fraction
patch_dim = np.int(math.floor(math.sqrt(patch_area)))
if patch_area == 0 or patch_dim == 0:
return mask
x = np.random.randint(shape[0] - patch_dim)
y = np.random.randint(shape[1] - patch_dim)
mask[x:(x + patch_dim), y:(y + patch_dim), :] = 0
return mask |
<SYSTEM_TASK:>
Base problem example generator for Allen Brain Atlas problems.
<END_TASK>
<USER_TASK:>
Description:
def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE,
training_fraction=0.95):
"""Base problem example generator for Allen Brain Atlas problems.
Args:
tmp_dir: str, a directory where raw example input data has been stored.
training: bool, whether the mode of operation is training (or,
alternatively, evaluation), determining whether examples in tmp_dir
prefixed with train or dev will be used.
size: int, the image size to add to the example annotation.
training_fraction: float, the fraction of the sub-image path list to
consider as the basis for training examples.
Yields:
A dictionary representing the images with the following fields:
* image/encoded: The string encoding the image as JPEG.
* image/format: The string "jpeg" indicating the image format.
* image/height: The integer indicating the image height.
* image/width: The integer indicating the image height.
""" |
maybe_download_image_dataset(_IMAGE_IDS, tmp_dir)
image_files = _get_case_file_paths(tmp_dir=tmp_dir,
case=training,
training_fraction=training_fraction)
image_obj = PIL_Image()
tf.logging.info("Loaded case file paths (n=%s)" % len(image_files))
height = size
width = size
for input_path in image_files:
img = image_obj.open(input_path)
img = np.float32(img)
shape = np.shape(img)
for h_index in range(0, int(math.floor(shape[0]/size))):
h_offset = h_index * size
h_end = h_offset + size - 1
for v_index in range(0, int(math.floor(shape[1]/size))):
v_offset = v_index * size
v_end = v_offset + size - 1
# Extract a sub-image tile.
subimage = np.uint8(img[h_offset:h_end, v_offset:v_end]) # pylint: disable=invalid-sequence-index
# Filter images that are likely background (not tissue).
if np.amax(subimage) < 230:
continue
subimage = image_obj.fromarray(subimage)
buff = BytesIO()
subimage.save(buff, format="JPEG")
subimage_encoded = buff.getvalue()
yield {
"image/encoded": [subimage_encoded],
"image/format": ["jpeg"],
"image/height": [height],
"image/width": [width]
} |
<SYSTEM_TASK:>
Base transformers model with moe.
<END_TASK>
<USER_TASK:>
Description:
def transformer_moe_2k():
"""Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-attention - enco/deco-attention - masked sep)
* Layer 1: a - a - sepm
* Layer 2: a - a - moe (mixture of expert layers in the middle)
* Layer 3: a - a - sepm
* Layer 4: a - a - sepm
Returns:
hparams
""" |
hparams = transformer_moe_8k()
hparams.batch_size = 2048
hparams.default_ff = "sep"
# hparams.layer_types contains the network architecture:
encoder_archi = "a/a/a/a/a"
decoder_archi = "a-sepm/a-sepm/a-moe/a-sepm/a-sepm"
hparams.layer_types = "{}#{}".format(encoder_archi, decoder_archi)
return hparams |
<SYSTEM_TASK:>
Model which formulate a seq2seq problem as language modeling.
<END_TASK>
<USER_TASK:>
Description:
def transformer_moe_prepend_8k():
"""Model which formulate a seq2seq problem as language modeling.""" |
hparams = transformer_moe_8k()
hparams.prepend_mode = "prepend_inputs_masked_attention"
hparams.eval_drop_long_sequences = False
hparams.max_input_seq_length = 7500
hparams.default_ff = "sepm"
hparams.layer_types = "locm/redm/locm-moe/redm/locm"
hparams.moe_num_experts = 256
return hparams |
<SYSTEM_TASK:>
Applies residual function for RevNet.
<END_TASK>
<USER_TASK:>
Description:
def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1,
training=True, bottleneck=True, padding='SAME'):
"""Applies residual function for RevNet.
Args:
x: input tensor
depth1: Number of output channels for the first and second conv layers.
depth2: Number of output channels for the third conv layer.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
first_batch_norm: Whether to keep the first batch norm layer or not.
Typically used in the first RevNet block.
stride: Stride for the first conv filter. Note that this particular
RevNet architecture only varies the stride for the first conv
filter. The stride for the second conv filter is always set to 1.
training: True for train phase, False for eval phase.
bottleneck: If true, apply bottleneck 1x1 down/up sampling.
padding: Padding for each conv layer.
Returns:
Output tensor after applying residual function for RevNet.
""" |
conv = CONFIG[dim]['conv']
with tf.variable_scope('f', reuse=tf.AUTO_REUSE):
if first_batch_norm:
net = tf.layers.batch_normalization(x, training=training)
net = tf.nn.relu(net)
else:
net = x
if bottleneck:
net = conv(net, depth1, 1, strides=stride,
padding=padding, activation=None)
net = tf.layers.batch_normalization(net, training=training)
net = tf.nn.relu(net)
net = conv(net, depth1, 3, strides=1,
padding=padding, activation=None)
net = tf.layers.batch_normalization(net, training=training)
net = tf.nn.relu(net)
net = conv(net, depth2, 1, strides=1,
padding=padding, activation=None)
else:
net = conv(net, depth2, 3, strides=stride,
padding=padding, activation=None)
net = tf.layers.batch_normalization(x, training=training)
net = tf.nn.relu(net)
net = conv(net, depth2, 3, strides=stride,
padding=padding, activation=None)
return net |
<SYSTEM_TASK:>
Downsamples 'x' by `stride` using a 1x1 convolution filter.
<END_TASK>
<USER_TASK:>
Description:
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'):
"""Downsamples 'x' by `stride` using a 1x1 convolution filter.
Args:
x: input tensor of size [N, H, W, C]
output_channels: Desired number of output channels.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: What stride to use. Usually 1 or 2.
scope: Optional variable scope.
Returns:
A downsampled tensor of size [N, H/2, W/2, output_channels] if stride
is 2, else returns a tensor of size [N, H, W, output_channels] if
stride is 1.
""" |
conv = CONFIG[dim]['conv']
with tf.variable_scope(scope):
x = conv(x, output_channels, 1, strides=stride, padding='SAME',
activation=None)
return x |
<SYSTEM_TASK:>
Downsamples 'x' by `stride` using average pooling.
<END_TASK>
<USER_TASK:>
Description:
def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'):
"""Downsamples 'x' by `stride` using average pooling.
Args:
x: input tensor of size [N, H, W, C]
output_channels: Desired number of output channels.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: What stride to use. Usually 1 or 2.
scope: Optional variable scope.
Returns:
A downsampled tensor of size [N, H/2, W/2, output_channels] if stride
is 2, else returns a tensor of size [N, H, W, output_channels] if
stride is 1.
""" |
with tf.variable_scope(scope):
if stride > 1:
avg_pool = CONFIG[dim]['avg_pool']
x = avg_pool(x,
pool_size=(stride, stride),
strides=(stride, stride),
padding='VALID')
input_channels = tf.shape(x)[3]
diff = output_channels - input_channels
x = tf.pad(
x, [[0, 0], [0, 0], [0, 0],
[diff // 2, diff // 2]])
return x |
<SYSTEM_TASK:>
Standard ResNet initial block used as first RevNet block.
<END_TASK>
<USER_TASK:>
Description:
def init(images, num_channels, dim='2d', stride=2,
kernel_size=7, maxpool=True, training=True, scope='init'):
"""Standard ResNet initial block used as first RevNet block.
Args:
images: [N, H, W, 3] tensor of input images to the model.
num_channels: Output depth of convolutional layer in initial block.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: stride for the convolution and pool layer.
kernel_size: Size of the initial convolution filter
maxpool: If true, apply a maxpool after the convolution
training: True for train phase, False for eval phase.
scope: Optional scope for the init block.
Returns:
Two [N, H, W, C] output activations from input images.
""" |
conv = CONFIG[dim]['conv']
pool = CONFIG[dim]['max_pool']
with tf.variable_scope(scope):
net = conv(images, num_channels, kernel_size, strides=stride,
padding='SAME', activation=None)
net = tf.layers.batch_normalization(net, training=training)
net = tf.nn.relu(net)
if maxpool:
net = pool(net, pool_size=3, strides=stride)
x1, x2 = tf.split(net, 2, axis=CONFIG[dim]['split_axis'])
return x1, x2 |
<SYSTEM_TASK:>
Implements bottleneck RevNet unit from authors' RevNet architecture.
<END_TASK>
<USER_TASK:>
Description:
def unit(x1, x2, block_num, depth, num_layers, dim='2d',
bottleneck=True, first_batch_norm=True, stride=1, training=True):
"""Implements bottleneck RevNet unit from authors' RevNet architecture.
Args:
x1: [N, H, W, C] tensor of network activations.
x2: [N, H, W, C] tensor of network activations.
block_num: integer ID of block
depth: First depth in bottleneck residual unit.
num_layers: Number of layers in the RevNet block.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
bottleneck: Should a bottleneck layer be used.
first_batch_norm: Whether to keep the first batch norm layer or not.
Typically used in the first RevNet block.
stride: Stride for the residual function.
training: True for train phase, False for eval phase.
Returns:
Two [N, H, W, C] output activation tensors.
""" |
scope_name = 'unit_%d' % block_num
if bottleneck:
depth1 = depth
depth2 = depth * 4
else:
depth1 = depth2 = depth
residual = wrapped_partial(f,
depth1=depth1, depth2=depth2, dim=dim,
training=training, bottleneck=bottleneck)
with tf.variable_scope(scope_name):
downsample = downsample_bottleneck if bottleneck else downsample_residual
# Manual implementation of downsampling
with tf.variable_scope('downsampling'):
with tf.variable_scope('x1'):
hx1 = downsample(x1, depth2, dim=dim, stride=stride)
fx2 = residual(x2, stride=stride, first_batch_norm=first_batch_norm)
x1 = hx1 + fx2
with tf.variable_scope('x2'):
hx2 = downsample(x2, depth2, dim=dim, stride=stride)
fx1 = residual(x1)
x2 = hx2 + fx1
# Full block using memory-efficient rev_block implementation.
with tf.variable_scope('full_block'):
x1, x2 = tf.contrib.layers.rev_block(x1, x2,
residual,
residual,
num_layers=num_layers)
return x1, x2 |
<SYSTEM_TASK:>
Converts activations from last RevNet block to pre-logits.
<END_TASK>
<USER_TASK:>
Description:
def final_block(x1, x2, dim='2d', training=True, scope='final_block'):
"""Converts activations from last RevNet block to pre-logits.
Args:
x1: [NxHxWxC] tensor of network activations.
x2: [NxHxWxC] tensor of network activations.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
training: True for train phase, False for eval phase.
scope: Optional variable scope for the final block.
Returns:
[N, hidden_dim] pre-logits tensor from activations x1 and x2.
""" |
# Final batch norm and relu
with tf.variable_scope(scope):
y = tf.concat([x1, x2], axis=CONFIG[dim]['split_axis'])
y = tf.layers.batch_normalization(y, training=training)
y = tf.nn.relu(y)
# Global average pooling
net = tf.reduce_mean(y, CONFIG[dim]['reduction_dimensions'],
name='final_pool', keep_dims=True)
return net |
<SYSTEM_TASK:>
Uses Tensor2Tensor memory optimized RevNet block to build a RevNet.
<END_TASK>
<USER_TASK:>
Description:
def revnet(inputs, hparams, reuse=None):
"""Uses Tensor2Tensor memory optimized RevNet block to build a RevNet.
Args:
inputs: [NxHxWx3] tensor of input images to the model.
hparams: HParams object that contains the following parameters,
in addition to the parameters contained in the basic_params1() object in
the common_hparams module:
num_channels_first - A Python list where each element represents the
depth of the first and third convolutional layers in the bottleneck
residual unit for a given block.
num_channels_second - A Python list where each element represents the
depth of the second convolutional layer in the bottleneck residual
unit for a given block.
num_layers_per_block - A Python list containing the number of RevNet
layers for each block.
first_batch_norm - A Python list containing booleans representing the
presence of a batch norm layer at the beginning of a given block.
strides - A Python list containing integers representing the stride of
the residual function for each block.
num_channels_init_block - An integer representing the number of channels
for the convolutional layer in the initial block.
dimension - A string (either "2d" or "3d") that decides if the RevNet is
2-dimensional or 3-dimensional.
reuse: Whether to reuse the default variable scope.
Returns:
[batch_size, hidden_dim] pre-logits tensor from the bottleneck RevNet.
""" |
training = hparams.mode == tf.estimator.ModeKeys.TRAIN
with tf.variable_scope('RevNet', reuse=reuse):
x1, x2 = init(inputs,
num_channels=hparams.num_channels_init_block,
dim=hparams.dim,
kernel_size=hparams.init_kernel_size,
maxpool=hparams.init_maxpool,
stride=hparams.init_stride,
training=training)
for block_num in range(len(hparams.num_layers_per_block)):
block = {'depth': hparams.num_channels[block_num],
'num_layers': hparams.num_layers_per_block[block_num],
'first_batch_norm': hparams.first_batch_norm[block_num],
'stride': hparams.strides[block_num],
'bottleneck': hparams.bottleneck}
x1, x2 = unit(x1, x2, block_num, dim=hparams.dim, training=training,
**block)
pre_logits = final_block(x1, x2, dim=hparams.dim, training=training)
return pre_logits |
<SYSTEM_TASK:>
Basic conv model with scheduled sampling.
<END_TASK>
<USER_TASK:>
Description:
def next_frame_sampling():
"""Basic conv model with scheduled sampling.""" |
hparams = next_frame_basic_deterministic()
hparams.scheduled_sampling_mode = "prob_inverse_exp"
hparams.scheduled_sampling_max_prob = 1.0
hparams.scheduled_sampling_decay_steps = 10000
return hparams |
<SYSTEM_TASK:>
Basic conv model with L1 modality.
<END_TASK>
<USER_TASK:>
Description:
def next_frame_l1():
"""Basic conv model with L1 modality.""" |
hparams = next_frame_basic_deterministic()
hparams.loss["targets"] = modalities.video_l1_loss
hparams.top["targets"] = modalities.video_l1_top
hparams.video_modality_loss_cutoff = 2.4
return hparams |
<SYSTEM_TASK:>
Initializes env_specs using the appropriate env.
<END_TASK>
<USER_TASK:>
Description:
def initialize_env_specs(hparams, env_problem_name):
"""Initializes env_specs using the appropriate env.""" |
if env_problem_name:
env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size)
else:
env = rl_utils.setup_env(hparams, hparams.batch_size,
hparams.eval_max_num_noops,
hparams.rl_env_max_episode_steps,
env_name=hparams.rl_env_name)
env.start_new_epoch(0)
return rl.make_real_env_fn(env) |
<SYSTEM_TASK:>
Compute the designated learning rate factor from hparams.
<END_TASK>
<USER_TASK:>
Description:
def learning_rate_factor(name, step_num, hparams):
"""Compute the designated learning rate factor from hparams.""" |
if name == "constant":
tf.logging.info("Base learning rate: %f", hparams.learning_rate_constant)
return hparams.learning_rate_constant
elif name == "linear_warmup":
return tf.minimum(1.0, step_num / hparams.learning_rate_warmup_steps)
elif name == "linear_decay":
ret = (hparams.train_steps - step_num) / hparams.learning_rate_decay_steps
return tf.minimum(1.0, tf.maximum(0.0, ret))
elif name == "cosdecay": # openai gpt
in_warmup = tf.cast(step_num <= hparams.learning_rate_warmup_steps,
dtype=tf.float32)
ret = 0.5 * (1 + tf.cos(
np.pi * step_num / hparams.learning_rate_decay_steps))
# if in warmup stage return 1 else return the decayed value
return in_warmup * 1 + (1 - in_warmup) * ret
elif name == "single_cycle_cos_decay":
# Cosine decay to zero with a single cycle. This is different from
# "cosdecay" because it starts at 1 when the warmup steps end.
x = tf.maximum(step_num, hparams.learning_rate_warmup_steps)
step = x - hparams.learning_rate_warmup_steps
return tf.math.cos(
step * np.pi / hparams.learning_rate_decay_steps) / 2.0 + 0.5
elif name == "rsqrt_decay":
return tf.rsqrt(tf.maximum(step_num, hparams.learning_rate_warmup_steps))
elif name == "rsqrt_normalized_decay":
scale = tf.sqrt(tf.to_float(hparams.learning_rate_warmup_steps))
return scale * tf.rsqrt(tf.maximum(
step_num, hparams.learning_rate_warmup_steps))
elif name == "exp_decay":
decay_steps = hparams.learning_rate_decay_steps
warmup_steps = hparams.learning_rate_warmup_steps
p = (step_num - warmup_steps) / decay_steps
p = tf.maximum(p, 0.)
if hparams.learning_rate_decay_staircase:
p = tf.floor(p)
return tf.pow(hparams.learning_rate_decay_rate, p)
elif name == "rsqrt_hidden_size":
return hparams.hidden_size ** -0.5
elif name == "legacy":
return legacy_learning_rate_schedule(hparams)
else:
raise ValueError("unknown learning rate factor %s" % name) |
<SYSTEM_TASK:>
Learning rate schedule based on hparams.
<END_TASK>
<USER_TASK:>
Description:
def learning_rate_schedule(hparams):
"""Learning rate schedule based on hparams.""" |
mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True)
mlperf_log.transformer_print(
key=mlperf_log.OPT_LR_WARMUP_STEPS,
value=hparams.learning_rate_warmup_steps)
step_num = _global_step(hparams)
schedule_string = hparams.learning_rate_schedule
names = schedule_string.split("*")
names = [name.strip() for name in names if name.strip()]
ret = tf.constant(1.0)
for name in names:
ret *= learning_rate_factor(name, step_num, hparams)
return ret |
<SYSTEM_TASK:>
Adjust global step if a multi-step optimizer is used.
<END_TASK>
<USER_TASK:>
Description:
def _global_step(hparams):
"""Adjust global step if a multi-step optimizer is used.""" |
step = tf.to_float(tf.train.get_or_create_global_step())
multiplier = hparams.optimizer_multistep_accumulate_steps
if not multiplier:
return step
tf.logging.info("Dividing global step by %d for multi-step optimizer."
% multiplier)
return step / tf.to_float(multiplier) |
<SYSTEM_TASK:>
Scale learning rate according to the given schedule.
<END_TASK>
<USER_TASK:>
Description:
def _piecewise_learning_rate(step, boundaries, values):
"""Scale learning rate according to the given schedule.
Multipliers are not cumulative.
Args:
step: global step
boundaries: List of steps to transition on.
values: Multiplier to apply at each boundary transition.
Returns:
Scaled value for the learning rate.
""" |
values = [1.0] + values
boundaries = [float(x) for x in boundaries]
return tf.train.piecewise_constant(
step, boundaries, values, name="piecewise_lr") |
<SYSTEM_TASK:>
Returns True if `find` is a subtree of `expr`.
<END_TASK>
<USER_TASK:>
Description:
def is_in_expr(expr, find):
"""Returns True if `find` is a subtree of `expr`.""" |
return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find)) |
<SYSTEM_TASK:>
Generate a random expression tree with a required variable.
<END_TASK>
<USER_TASK:>
Description:
def random_expr_with_required_var(depth, required_var, optional_list, ops):
"""Generate a random expression tree with a required variable.
The required variable appears exactly once in the expression.
Args:
depth: At least one leaf will be this many levels down from the top.
required_var: A char. This char is guaranteed to be placed exactly once at
a leaf somewhere in the tree. This is the var to solve for.
optional_list: A list of chars. These chars are randomly selected as leaf
values. These are constant vars.
ops: A list of ExprOp instances.
Returns:
An ExprNode instance which is the root of the generated expression tree.
""" |
if not depth:
if required_var:
return required_var
return str(optional_list[random.randrange(len(optional_list))])
max_depth_side = random.randrange(2)
other_side_depth = random.randrange(depth)
required_var_side = random.randrange(2)
left = random_expr_with_required_var(
depth - 1 if max_depth_side else other_side_depth, required_var
if required_var_side else None, optional_list, ops)
right = random_expr_with_required_var(
depth - 1 if not max_depth_side else other_side_depth, required_var
if not required_var_side else None, optional_list, ops)
op = ops[random.randrange(len(ops))]
return ExprNode(left, right, op) |
<SYSTEM_TASK:>
Generate a random expression tree.
<END_TASK>
<USER_TASK:>
Description:
def random_expr(depth, vlist, ops):
"""Generate a random expression tree.
Args:
depth: At least one leaf will be this many levels down from the top.
vlist: A list of chars. These chars are randomly selected as leaf values.
ops: A list of ExprOp instances.
Returns:
An ExprNode instance which is the root of the generated expression tree.
""" |
if not depth:
return str(vlist[random.randrange(len(vlist))])
max_depth_side = random.randrange(2)
other_side_depth = random.randrange(depth)
left = random_expr(depth - 1
if max_depth_side else other_side_depth, vlist, ops)
right = random_expr(depth - 1
if not max_depth_side else other_side_depth, vlist, ops)
op = ops[random.randrange(len(ops))]
return ExprNode(left, right, op) |
<SYSTEM_TASK:>
Solves for the value of the given var in an expression.
<END_TASK>
<USER_TASK:>
Description:
def algebra_inverse_solve(left, right, var, solve_ops):
"""Solves for the value of the given var in an expression.
Args:
left: The root of the ExprNode tree on the left side of the equals sign.
right: The root of the ExprNode tree on the right side of the equals sign.
var: A char. The variable to solve for.
solve_ops: A dictionary with the following properties.
* For each operator in the expression, there is a rule that determines
how to cancel out a value either to the left or the right of that
operator.
* For each rule, there is an entry in the dictionary. The key is two
chars- the op char, and either 'l' or 'r' meaning rule for canceling
out the left or right sides. For example, '+l', '+r', '-l', '-r'.
* The value of each entry is a function with the following signature:
(left, right, to_tree) -> (new_from_tree, new_to_tree)
left- Expression on left side of the op.
right- Expression on the right side of the op.
to_tree- The tree on the other side of the equal sign. The canceled
out expression will be moved here.
new_from_tree- The resulting from_tree after the algebraic
manipulation.
new_to_tree- The resulting to_tree after the algebraic manipulation.
Returns:
The root of an ExprNode tree which holds the value of `var` after solving.
Raises:
ValueError: If `var` does not appear exactly once in the equation (which
includes the left and right sides).
""" |
is_in_left = is_in_expr(left, var)
is_in_right = is_in_expr(right, var)
if is_in_left == is_in_right:
if is_in_left:
raise ValueError("Solve-variable '%s' is on both sides of the equation. "
"Only equations where the solve variable-appears once "
"are supported by this solver. Left: '%s', right: '%s'" %
(var, str(left), str(right)))
else:
raise ValueError("Solve-variable '%s' is not present in the equation. It "
"must appear once. Left: '%s', right: '%s'" %
(var, str(left), str(right)))
from_tree = left if is_in_left else right
to_tree = left if not is_in_left else right
while from_tree != var:
is_in_left = is_in_expr(from_tree.left, var)
is_in_right = is_in_expr(from_tree.right, var)
from_tree, to_tree = (solve_ops[str(from_tree.op)
+ ("l" if is_in_left else "r")](
from_tree.left, from_tree.right,
to_tree))
return to_tree |
<SYSTEM_TASK:>
Convert sympy expression into a string which can be encoded.
<END_TASK>
<USER_TASK:>
Description:
def format_sympy_expr(sympy_expr, functions=None):
"""Convert sympy expression into a string which can be encoded.
Args:
sympy_expr: Any sympy expression tree or string.
functions: Defines special functions. A dict mapping human readable string
names, like "log", "exp", "sin", "cos", etc., to single chars. Each
function gets a unique token, like "L" for "log".
Returns:
A string representation of the expression suitable for encoding as a
sequence input.
""" |
if functions is None:
functions = {}
str_expr = str(sympy_expr)
result = str_expr.replace(" ", "")
for fn_name, char in six.iteritems(functions):
result = result.replace(fn_name, char)
return result |
<SYSTEM_TASK:>
Randomly generate an algebra inverse dataset sample.
<END_TASK>
<USER_TASK:>
Description:
def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth,
max_depth):
"""Randomly generate an algebra inverse dataset sample.
Given an input equation and variable, produce the expression equal to the
variable.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
solve_ops: See `solve_ops` documentation in `algebra_inverse_solve`.
min_depth: Expression trees will not have a smaller depth than this. 0 means
there is just a variable. 1 means there is one operation.
max_depth: Expression trees will not have a larger depth than this. To make
all trees have the same depth, set this equal to `min_depth`.
Returns:
sample: String representation of the input. Will be of the form
'solve_var:left_side=right_side'.
target: String representation of the solution.
""" |
side = random.randrange(2)
left_depth = random.randrange(min_depth if side else 0, max_depth + 1)
right_depth = random.randrange(min_depth if not side else 0, max_depth + 1)
var_index = random.randrange(len(vlist))
var = vlist[var_index]
consts = vlist[:var_index] + vlist[var_index + 1:]
left = random_expr_with_required_var(left_depth, var
if side else None, consts, ops)
right = random_expr_with_required_var(right_depth, var
if not side else None, consts, ops)
left_str = str(left)
right_str = str(right)
target = str(algebra_inverse_solve(left, right, var, solve_ops))
sample = "%s:%s=%s" % (var, left_str, right_str)
return sample, target |
<SYSTEM_TASK:>
Randomly generate an algebra simplify dataset sample.
<END_TASK>
<USER_TASK:>
Description:
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth):
"""Randomly generate an algebra simplify dataset sample.
Given an input expression, produce the simplified expression.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
min_depth: Expression trees will not have a smaller depth than this. 0 means
there is just a variable. 1 means there is one operation.
max_depth: Expression trees will not have a larger depth than this. To make
all trees have the same depth, set this equal to `min_depth`.
Returns:
sample: String representation of the input.
target: String representation of the solution.
""" |
depth = random.randrange(min_depth, max_depth + 1)
expr = random_expr(depth, vlist, ops)
sample = str(expr)
target = format_sympy_expr(sympy.simplify(sample))
return sample, target |
<SYSTEM_TASK:>
Randomly generate a symbolic integral dataset sample.
<END_TASK>
<USER_TASK:>
Description:
def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth,
functions):
"""Randomly generate a symbolic integral dataset sample.
Given an input expression, produce the indefinite integral.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
min_depth: Expression trees will not have a smaller depth than this. 0 means
there is just a variable. 1 means there is one operation.
max_depth: Expression trees will not have a larger depth than this. To make
all trees have the same depth, set this equal to `min_depth`.
functions: Defines special functions. A dict mapping human readable string
names, like "log", "exp", "sin", "cos", etc., to single chars. Each
function gets a unique token, like "L" for "log".
Returns:
sample: String representation of the input. Will be of the form
'var:expression'.
target: String representation of the solution.
""" |
var_index = random.randrange(len(vlist))
var = vlist[var_index]
consts = vlist[:var_index] + vlist[var_index + 1:]
depth = random.randrange(min_depth, max_depth + 1)
expr = random_expr_with_required_var(depth, var, consts, ops)
expr_str = str(expr)
sample = var + ":" + expr_str
target = format_sympy_expr(
sympy.integrate(expr_str, sympy.Symbol(var)), functions=functions)
return sample, target |
<SYSTEM_TASK:>
Generate the algebra inverse dataset.
<END_TASK>
<USER_TASK:>
Description:
def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2,
nbr_cases=10000):
"""Generate the algebra inverse dataset.
Each sample is a symbolic math equation involving unknown variables. The
task is to solve for the given variable. The target is the resulting
expression.
Args:
alphabet_size: How many possible variables there are. Max 52.
min_depth: Minimum depth of the expression trees on both sides of the
equals sign in the equation.
max_depth: Maximum depth of the expression trees on both sides of the
equals sign in the equation.
nbr_cases: The number of cases to generate.
Yields:
A dictionary {"inputs": input-list, "targets": target-list} where
input-list are the tokens encoding the variable to solve for and the math
equation, and target-list is a list of tokens encoding the resulting math
expression after solving for the variable.
Raises:
ValueError: If `max_depth` < `min_depth`.
""" |
if max_depth < min_depth:
raise ValueError("max_depth must be greater than or equal to min_depth. "
"Got max_depth=%s, min_depth=%s" % (max_depth, min_depth))
alg_cfg = math_dataset_init(alphabet_size)
for _ in range(nbr_cases):
sample, target = generate_algebra_inverse_sample(
alg_cfg.vlist,
list(alg_cfg.ops.values()), alg_cfg.solve_ops, min_depth, max_depth)
yield {
"inputs": alg_cfg.int_encoder(sample),
"targets": alg_cfg.int_encoder(target)
} |
<SYSTEM_TASK:>
Generate the algebra simplify dataset.
<END_TASK>
<USER_TASK:>
Description:
def algebra_simplify(alphabet_size=26,
min_depth=0,
max_depth=2,
nbr_cases=10000):
"""Generate the algebra simplify dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to simplify the expression. The target is the resulting expression.
Args:
alphabet_size: How many possible variables there are. Max 52.
min_depth: Minimum depth of the expression trees on both sides of the
equals sign in the equation.
max_depth: Maximum depth of the expression trees on both sides of the
equals sign in the equation.
nbr_cases: The number of cases to generate.
Yields:
A dictionary {"inputs": input-list, "targets": target-list} where
input-list are the tokens encoding the expression to simplify, and
target-list is a list of tokens encoding the resulting math expression after
simplifying.
Raises:
ValueError: If `max_depth` < `min_depth`.
""" |
if max_depth < min_depth:
raise ValueError("max_depth must be greater than or equal to min_depth. "
"Got max_depth=%s, min_depth=%s" % (max_depth, min_depth))
alg_cfg = math_dataset_init(alphabet_size, digits=5)
for _ in range(nbr_cases):
sample, target = generate_algebra_simplify_sample(
alg_cfg.vlist, list(alg_cfg.ops.values()), min_depth, max_depth)
yield {
"inputs": alg_cfg.int_encoder(sample),
"targets": alg_cfg.int_encoder(target)
} |
<SYSTEM_TASK:>
Generate the calculus integrate dataset.
<END_TASK>
<USER_TASK:>
Description:
def calculus_integrate(alphabet_size=26,
min_depth=0,
max_depth=2,
nbr_cases=10000):
"""Generate the calculus integrate dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to take the indefinite integral of the expression. The target is the
resulting expression.
Args:
alphabet_size: How many possible variables there are. Max 26.
min_depth: Minimum depth of the expression trees on both sides of the
equals sign in the equation.
max_depth: Maximum depth of the expression trees on both sides of the
equals sign in the equation.
nbr_cases: The number of cases to generate.
Yields:
A dictionary {"inputs": input-list, "targets": target-list} where
input-list are the tokens encoding the variable to integrate with respect
to and the expression to integrate, and target-list is a list of tokens
encoding the resulting math expression after integrating.
Raises:
ValueError: If `max_depth` < `min_depth`, or if alphabet_size > 26.
""" |
if max_depth < min_depth:
raise ValueError("max_depth must be greater than or equal to min_depth. "
"Got max_depth=%s, min_depth=%s" % (max_depth, min_depth))
# Don't allow alphabet to use capital letters. Those are reserved for function
# names.
if alphabet_size > 26:
raise ValueError(
"alphabet_size must not be greater than 26. Got %s." % alphabet_size)
functions = {"log": "L"}
alg_cfg = math_dataset_init(alphabet_size, digits=5, functions=functions)
nbr_case = 0
while nbr_case < nbr_cases:
try:
sample, target = generate_calculus_integrate_sample(
alg_cfg.vlist,
list(alg_cfg.ops.values()), min_depth, max_depth, alg_cfg.functions)
yield {
"inputs": alg_cfg.int_encoder(sample),
"targets": alg_cfg.int_encoder(target)
}
except: # pylint:disable=bare-except
continue
if nbr_case % 10000 == 0:
print(" calculus_integrate: generating case %d." % nbr_case)
nbr_case += 1 |
<SYSTEM_TASK:>
Returns True if `expr` is a subtree.
<END_TASK>
<USER_TASK:>
Description:
def is_in(self, expr):
"""Returns True if `expr` is a subtree.""" |
if expr == self:
return True
is_in_left = is_in_expr(self.left, expr)
is_in_right = is_in_expr(self.right, expr)
return is_in_left or is_in_right |
<SYSTEM_TASK:>
Preprocessing steps common to all models.
<END_TASK>
<USER_TASK:>
Description:
def preprocess_example_common(example, mode, hparams):
"""Preprocessing steps common to all models.""" |
if "inputs" in example and hparams.max_input_seq_length > 0:
example["inputs"] = example["inputs"][:hparams.max_input_seq_length]
if hparams.prepend_mode != "none":
if mode == tf.estimator.ModeKeys.PREDICT:
example["partial_targets"] = tf.concat([example["inputs"], [0]], 0)
else:
example["targets"] = tf.concat(
[example["inputs"], [0], example["targets"]], 0)
if "targets" in example and hparams.max_target_seq_length > 0:
example["targets"] = example["targets"][:hparams.max_target_seq_length]
if hparams.split_to_length:
new_example = {}
for k, v in six.iteritems(example):
if k == "targets" or k == "inputs":
new_example[k] = tf.reshape(v, [-1, hparams.split_to_length, 1, 1])
else:
tf.logging.warning("Dropping feature %s" % k)
return tf.data.Dataset.from_tensor_slices(new_example)
return example |
<SYSTEM_TASK:>
Use input modality, vocab, and space id for target.
<END_TASK>
<USER_TASK:>
Description:
def _copy_problem_hparams(p_hparams):
"""Use input modality, vocab, and space id for target.""" |
p = p_hparams
# Duplicate input modality.
p.modality["targets"] = p.modality["inputs"]
# Duplicate input vocab size.
p.vocab_size["targets"] = p.vocab_size["inputs"]
# Duplicate input vocabulary.
p.vocabulary["targets"] = p.vocabulary["inputs"]
# Duplicate input space ids.
p.target_space_id = p.input_space_id
# Mark that p was reversed.
p.was_copy = True |
<SYSTEM_TASK:>
Batch size in examples per TPU core.
<END_TASK>
<USER_TASK:>
Description:
def tpu_batch_size_per_shard(self, model_hparams):
"""Batch size in examples per TPU core.
Args:
model_hparams: model hyperparameters
Returns:
an integer
""" |
if self.batch_size_means_tokens and not model_hparams.use_fixed_batch_size:
return model_hparams.batch_size // self.max_length(model_hparams)
else:
return model_hparams.batch_size |
<SYSTEM_TASK:>
Runtime preprocessing on the whole dataset.
<END_TASK>
<USER_TASK:>
Description:
def preprocess(self, dataset, mode, hparams, interleave=True):
"""Runtime preprocessing on the whole dataset.
Return a tf.data.Datset -- the preprocessed version of the given one.
By default this function calls preprocess_example.
Args:
dataset: the Dataset of already decoded but not yet preprocessed features.
mode: tf.estimator.ModeKeys
hparams: HParams, model hyperparameters
interleave: bool, whether to use parallel_interleave, which is faster
but will alter the order of samples non-deterministically, or flat_map,
which is slower but will preserve the sample order.
Returns:
a Dataset
""" |
def _preprocess(example):
examples = self.preprocess_example(example, mode, hparams)
if not isinstance(examples, tf.data.Dataset):
examples = tf.data.Dataset.from_tensors(examples)
return examples
if interleave:
dataset = dataset.apply(
tf.data.experimental.parallel_interleave(
_preprocess, sloppy=True, cycle_length=8))
else:
dataset = dataset.flat_map(_preprocess)
return dataset |
<SYSTEM_TASK:>
Get filepattern for data files for mode.
<END_TASK>
<USER_TASK:>
Description:
def filepattern(self, data_dir, mode, shard=None):
"""Get filepattern for data files for mode.
Matches mode to a suffix.
* DatasetSplit.TRAIN: train
* DatasetSplit.EVAL: dev
* DatasetSplit.TEST: test
* tf.estimator.ModeKeys.PREDICT: dev
Args:
data_dir: str, data directory.
mode: DatasetSplit
shard: int, if provided, will only read data from the specified shard.
Returns:
filepattern str
""" |
path = os.path.join(data_dir, self.dataset_filename())
shard_str = "-%05d" % shard if shard is not None else ""
if mode == DatasetSplit.TRAIN:
suffix = "train"
elif mode in [DatasetSplit.EVAL, tf.estimator.ModeKeys.PREDICT]:
suffix = "dev"
else:
assert mode == DatasetSplit.TEST
suffix = "test"
return "%s-%s%s*" % (path, suffix, shard_str) |
<SYSTEM_TASK:>
Reverse features between inputs and targets if the problem is '_rev'.
<END_TASK>
<USER_TASK:>
Description:
def maybe_reverse_features(self, feature_map):
"""Reverse features between inputs and targets if the problem is '_rev'.""" |
if not self._was_reversed:
return
inputs = feature_map.pop("inputs", None)
targets = feature_map.pop("targets", None)
inputs_seg = feature_map.pop("inputs_segmentation", None)
targets_seg = feature_map.pop("targets_segmentation", None)
inputs_pos = feature_map.pop("inputs_position", None)
targets_pos = feature_map.pop("targets_position", None)
if inputs is not None:
feature_map["targets"] = inputs
if targets is not None:
feature_map["inputs"] = targets
if inputs_seg is not None:
feature_map["targets_segmentation"] = inputs_seg
if targets_seg is not None:
feature_map["inputs_segmentation"] = targets_seg
if inputs_pos is not None:
feature_map["targets_position"] = inputs_pos
if targets_pos is not None:
feature_map["inputs_position"] = targets_pos |
<SYSTEM_TASK:>
Build a Dataset for this problem.
<END_TASK>
<USER_TASK:>
Description:
def dataset(self,
mode,
data_dir=None,
num_threads=None,
output_buffer_size=None,
shuffle_files=None,
hparams=None,
preprocess=True,
dataset_split=None,
shard=None,
partition_id=0,
num_partitions=1,
shuffle_buffer_size=1024,
max_records=-1):
"""Build a Dataset for this problem.
Args:
mode: tf.estimator.ModeKeys; determines which files to read from.
data_dir: directory that contains data files.
num_threads: int, number of threads to use for decode and preprocess
Dataset.map calls.
output_buffer_size: int, how many elements to prefetch at end of pipeline.
shuffle_files: whether to shuffle input files. Default behavior (i.e. when
shuffle_files=None) is to shuffle if mode == TRAIN.
hparams: HParams; hparams to be passed to
Problem.preprocess_example and Problem.hparams. If None, will use a
default set that is a no-op.
preprocess: bool, whether to map the Dataset through
Problem.preprocess_example.
dataset_split: DatasetSplit, which split to read data
from (TRAIN:"-train", EVAL:"-dev", "test":"-test"). Defaults to mode.
shard: int, if provided, will only read data from the specified shard.
partition_id: integer - which partition of the dataset to read from
num_partitions: how many partitions in the dataset
shuffle_buffer_size: if shuffle_files is True, this is the buffer size
used to shuffle records.
max_records: int, number of records to truncate to.
Returns:
Dataset containing dict<feature name, Tensor>.
Raises:
ValueError: if num_partitions is greater than the number of data files.
""" |
is_training = mode == tf.estimator.ModeKeys.TRAIN
shuffle_files = shuffle_files or shuffle_files is None and is_training
dataset_split = dataset_split or mode
assert data_dir
if hparams is None:
hparams = default_model_hparams()
if not hasattr(hparams, "data_dir"):
hparams.add_hparam("data_dir", data_dir)
if not hparams.data_dir:
hparams.data_dir = data_dir
# Construct the Problem's hparams so that items within it are accessible
_ = self.get_hparams(hparams)
data_filepattern = self.filepattern(data_dir, dataset_split, shard=shard)
tf.logging.info("Reading data files from %s", data_filepattern)
data_files = sorted(tf.contrib.slim.parallel_reader.get_data_files(
data_filepattern))
# Functions used in dataset transforms below. `filenames` can be either a
# `tf.string` tensor or `tf.data.Dataset` containing one or more filenames.
def _load_records_and_preprocess(filenames):
"""Reads files from a string tensor or a dataset of filenames."""
# Load records from file(s) with an 8MiB read buffer.
dataset = tf.data.TFRecordDataset(filenames, buffer_size=8 * 1024 * 1024)
# Decode.
dataset = dataset.map(self.decode_example, num_parallel_calls=num_threads)
# Preprocess if requested.
# Note that preprocessing should happen per-file as order may matter.
if preprocess:
dataset = self.preprocess(dataset, mode, hparams,
interleave=shuffle_files)
return dataset
if len(data_files) < num_partitions:
raise ValueError(
"number of data files (%d) must be at least the number of hosts (%d)"
% (len(data_files), num_partitions))
data_files = [f for (i, f) in enumerate(data_files)
if i % num_partitions == partition_id]
tf.logging.info(
"partition: %d num_data_files: %d" % (partition_id, len(data_files)))
if shuffle_files:
mlperf_log.transformer_print(key=mlperf_log.INPUT_ORDER)
random.shuffle(data_files)
dataset = tf.data.Dataset.from_tensor_slices(tf.constant(data_files))
# Create data-set from files by parsing, pre-processing and interleaving.
if shuffle_files:
dataset = dataset.apply(
tf.data.experimental.parallel_interleave(
_load_records_and_preprocess, sloppy=True, cycle_length=8))
else:
dataset = _load_records_and_preprocess(dataset)
dataset = dataset.map(
self.maybe_reverse_and_copy, num_parallel_calls=num_threads)
dataset = dataset.take(max_records)
## Shuffle records only for training examples.
if shuffle_files and is_training:
dataset = dataset.shuffle(shuffle_buffer_size)
if hparams.get("pack_dataset", False):
dataset = generator_utils.pack_dataset(
dataset, hparams.max_length, keys=["inputs", "targets"],
use_custom_ops=hparams.get("use_custom_ops", False))
if output_buffer_size:
dataset = dataset.prefetch(output_buffer_size)
return dataset |
<SYSTEM_TASK:>
Return a dict of Tensors from a serialized tensorflow.Example.
<END_TASK>
<USER_TASK:>
Description:
def decode_example(self, serialized_example):
"""Return a dict of Tensors from a serialized tensorflow.Example.""" |
data_fields, data_items_to_decoders = self.example_reading_spec()
# Necessary to rejoin examples in the correct order with the Cloud ML Engine
# batch prediction API.
data_fields["batch_prediction_key"] = tf.FixedLenFeature([1], tf.int64, 0)
if data_items_to_decoders is None:
data_items_to_decoders = {
field: tf.contrib.slim.tfexample_decoder.Tensor(field)
for field in data_fields
}
decoder = tf.contrib.slim.tfexample_decoder.TFExampleDecoder(
data_fields, data_items_to_decoders)
decode_items = list(sorted(data_items_to_decoders))
decoded = decoder.decode(serialized_example, items=decode_items)
return dict(zip(decode_items, decoded)) |
<SYSTEM_TASK:>
Return input_fn wrapped for Estimator.
<END_TASK>
<USER_TASK:>
Description:
def make_estimator_input_fn(self,
mode,
hparams,
data_dir=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
"""Return input_fn wrapped for Estimator.""" |
def estimator_input_fn(params, config):
return self.input_fn(
mode,
hparams,
data_dir=data_dir,
params=params,
config=config,
force_repeat=force_repeat,
prevent_repeat=prevent_repeat,
dataset_kwargs=dataset_kwargs)
return estimator_input_fn |
<SYSTEM_TASK:>
Which part of the training data to read.
<END_TASK>
<USER_TASK:>
Description:
def _dataset_partition(self, mode, config, params):
"""Which part of the training data to read.
If there are multiple parallel calls to input_fn (multiple TPU hosts),
then we want each one to read from a separate partition of the training
data.
Args:
mode: tf.estimator.ModeKeys
config: RunConfig
params: A dict that contains parameters.
Returns:
partition_id: an integer
num_partitions: an integer
""" |
if mode != tf.estimator.ModeKeys.TRAIN or not hasattr(config, "tpu_config"):
# Reset in the case when using TPU but alternating TRAIN and EVAL.
self._next_partition_id = 0
return 0, 1
phift = config.tpu_config.per_host_input_for_training
# This is the mesh-tensorflow case.
if (hasattr(tpu_config.InputPipelineConfig, "BROADCAST") and
phift == tpu_config.InputPipelineConfig.BROADCAST):
return 0, 1
if phift:
num_hosts = (params["context"].num_hosts if "context" in params
else config.tpu_config.num_shards // 8)
num_partitions = max(num_hosts, 1)
else:
num_partitions = config.tpu_config.num_shards
partition_id = getattr(self, "_next_partition_id", 0)
self._next_partition_id = partition_id + 1
tf.logging.info("num_partitions = %d partition_id = %d" %
(num_partitions, partition_id))
assert partition_id < num_partitions
return partition_id, num_partitions |
<SYSTEM_TASK:>
Input fn for serving export, starting from serialized example.
<END_TASK>
<USER_TASK:>
Description:
def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False):
"""Input fn for serving export, starting from serialized example.""" |
mode = tf.estimator.ModeKeys.PREDICT
serialized_example = tf.placeholder(
dtype=tf.string, shape=[None], name="serialized_example")
dataset = tf.data.Dataset.from_tensor_slices(serialized_example)
dataset = dataset.map(self.decode_example)
dataset = dataset.map(lambda ex: self.preprocess_example(ex, mode, hparams))
dataset = dataset.map(data_reader.cast_ints_to_int32)
if use_tpu:
padded_shapes = data_reader.pad_for_tpu(dataset.output_shapes, hparams,
hparams.max_length)
batch_size = 1 if not decode_hparams else getattr(decode_hparams,
"batch_size", 1)
dataset = dataset.padded_batch(
batch_size, padded_shapes, drop_remainder=False)
dataset = dataset.map(
functools.partial(data_reader.pad_batch, batch_multiple=batch_size))
else:
dataset = dataset.padded_batch(
tf.shape(serialized_example, out_type=tf.int64)[0],
dataset.output_shapes)
dataset = dataset.map(data_reader.standardize_shapes)
features = tf.data.experimental.get_single_element(dataset)
if self.has_inputs:
features.pop("targets", None)
return tf.estimator.export.ServingInputReceiver(
features=features, receiver_tensors=serialized_example) |
<SYSTEM_TASK:>
Exports given checkpoint as tfhub module with given spec.
<END_TASK>
<USER_TASK:>
Description:
def export_module_spec_with_checkpoint(module_spec,
checkpoint_path,
export_path,
scope_prefix=""):
"""Exports given checkpoint as tfhub module with given spec.""" |
# The main requirement is that it is possible to know how to map from
# module variable name to checkpoint variable name.
# This is trivial if the original code used variable scopes,
# but can be messy if the variables to export are interwined
# with variables not export.
with tf.Graph().as_default():
m = hub.Module(module_spec)
assign_map = {
scope_prefix + name: value for name, value in m.variable_map.items()
}
tf.train.init_from_checkpoint(checkpoint_path, assign_map)
init_op = tf.initializers.global_variables()
with tf.Session() as session:
session.run(init_op)
m.export(export_path, session) |
<SYSTEM_TASK:>
Exports the last checkpoint from the directory as tfhub module.
<END_TASK>
<USER_TASK:>
Description:
def export_as_tfhub_module(model_name,
hparams,
decode_hparams,
problem,
checkpoint_path,
export_dir):
"""Exports the last checkpoint from the directory as tfhub module.
It creates the Module spec and signature (based on T2T problem information),
which is later used to create and export the hub module.
Module will be saved inside the ckpt_dir.
Args:
model_name: name of the model to be exported.
hparams: T2T parameters, model graph will be based on them.
decode_hparams: T2T parameters for decoding.
problem: the name of the problem
checkpoint_path: path to the checkpoint to be exported.
export_dir: Directory to write the exported model to.
""" |
def hub_module_fn():
"""Creates the TF graph for the hub module."""
model_fn = t2t_model.T2TModel.make_estimator_model_fn(
model_name,
hparams,
decode_hparams=decode_hparams,
use_tpu=FLAGS.use_tpu)
features = problem.serving_input_fn(
hparams, decode_hparams, use_tpu=FLAGS.use_tpu).features
# we must do a copy of the features, as the model_fn can add additional
# entries there (like hyperparameter settings etc).
original_features = features.copy()
spec = model_fn(features, labels=None, mode=tf.estimator.ModeKeys.PREDICT)
hub.add_signature(
inputs=original_features,
outputs=spec.export_outputs["serving_default"].outputs)
# TFHub doesn't support the following collections.
drop_collections = [tf.GraphKeys.LOSSES,
tf.GraphKeys.SUMMARIES, tf.GraphKeys.LOCAL_VARIABLES]
module_spec = hub.create_module_spec(
hub_module_fn, drop_collections=drop_collections)
# Loads the weights from the checkpoint using the model above
# and saves it in the export_path.
export_module_spec_with_checkpoint(
module_spec,
checkpoint_path=checkpoint_path,
export_path=export_dir,
scope_prefix="") |
<SYSTEM_TASK:>
Build the graph required to fetch the attention weights.
<END_TASK>
<USER_TASK:>
Description:
def build_model(hparams_set, model_name, data_dir, problem_name, beam_size=1):
"""Build the graph required to fetch the attention weights.
Args:
hparams_set: HParams set to build the model with.
model_name: Name of model.
data_dir: Path to directory containing training data.
problem_name: Name of problem.
beam_size: (Optional) Number of beams to use when decoding a translation.
If set to 1 (default) then greedy decoding is used.
Returns:
Tuple of (
inputs: Input placeholder to feed in ids to be translated.
targets: Targets placeholder to feed to translation when fetching
attention weights.
samples: Tensor representing the ids of the translation.
att_mats: Tensors representing the attention weights.
)
""" |
hparams = trainer_lib.create_hparams(
hparams_set, data_dir=data_dir, problem_name=problem_name)
translate_model = registry.model(model_name)(
hparams, tf.estimator.ModeKeys.EVAL)
inputs = tf.placeholder(tf.int32, shape=(1, None, 1, 1), name="inputs")
targets = tf.placeholder(tf.int32, shape=(1, None, 1, 1), name="targets")
translate_model({
"inputs": inputs,
"targets": targets,
})
# Must be called after building the training graph, so that the dict will
# have been filled with the attention tensors. BUT before creating the
# inference graph otherwise the dict will be filled with tensors from
# inside a tf.while_loop from decoding and are marked unfetchable.
att_mats = get_att_mats(translate_model)
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
samples = translate_model.infer({
"inputs": inputs,
}, beam_size=beam_size)["outputs"]
return inputs, targets, samples, att_mats |
<SYSTEM_TASK:>
Get's the tensors representing the attentions from a build model.
<END_TASK>
<USER_TASK:>
Description:
def get_att_mats(translate_model):
"""Get's the tensors representing the attentions from a build model.
The attentions are stored in a dict on the Transformer object while building
the graph.
Args:
translate_model: Transformer object to fetch the attention weights from.
Returns:
Tuple of attention matrices; (
enc_atts: Encoder self attention weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, inp_len, inp_len)
dec_atts: Decoder self attetnion weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, out_len, out_len)
encdec_atts: Encoder-Decoder attention weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, out_len, inp_len)
)
""" |
enc_atts = []
dec_atts = []
encdec_atts = []
prefix = "transformer/body/"
postfix_self_attention = "/multihead_attention/dot_product_attention"
if translate_model.hparams.self_attention_type == "dot_product_relative":
postfix_self_attention = ("/multihead_attention/"
"dot_product_attention_relative")
postfix_encdec = "/multihead_attention/dot_product_attention"
for i in range(translate_model.hparams.num_hidden_layers):
enc_att = translate_model.attention_weights[
"%sencoder/layer_%i/self_attention%s"
% (prefix, i, postfix_self_attention)]
dec_att = translate_model.attention_weights[
"%sdecoder/layer_%i/self_attention%s"
% (prefix, i, postfix_self_attention)]
encdec_att = translate_model.attention_weights[
"%sdecoder/layer_%i/encdec_attention%s" % (prefix, i, postfix_encdec)]
enc_atts.append(enc_att)
dec_atts.append(dec_att)
encdec_atts.append(encdec_att)
return enc_atts, dec_atts, encdec_atts |
<SYSTEM_TASK:>
Input str to features dict, ready for inference.
<END_TASK>
<USER_TASK:>
Description:
def encode(self, input_str):
"""Input str to features dict, ready for inference.""" |
inputs = self.encoders["inputs"].encode(input_str) + [EOS_ID]
batch_inputs = np.reshape(inputs, [1, -1, 1, 1]) # Make it 3D.
return batch_inputs |
<SYSTEM_TASK:>
List of ints to list of str.
<END_TASK>
<USER_TASK:>
Description:
def decode_list(self, integers):
"""List of ints to list of str.""" |
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode_list(integers) |
<SYSTEM_TASK:>
Constructs the data needed for visualizing attentions.
<END_TASK>
<USER_TASK:>
Description:
def get_vis_data_from_string(self, sess, input_string):
"""Constructs the data needed for visualizing attentions.
Args:
sess: A tf.Session object.
input_string: The input sentence to be translated and visualized.
Returns:
Tuple of (
output_string: The translated sentence.
input_list: Tokenized input sentence.
output_list: Tokenized translation.
att_mats: Tuple of attention matrices; (
enc_atts: Encoder self attention weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, inp_len, inp_len)
dec_atts: Decoder self attention weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, out_len, out_len)
encdec_atts: Encoder-Decoder attention weights.
A list of `num_layers` numpy arrays of size
(batch_size, num_heads, out_len, inp_len)
)
""" |
encoded_inputs = self.encode(input_string)
# Run inference graph to get the translation.
out = sess.run(self.samples, {
self.inputs: encoded_inputs,
})
# Run the decoded translation through the training graph to get the
# attention tensors.
att_mats = sess.run(self.att_mats, {
self.inputs: encoded_inputs,
self.targets: np.reshape(out, [1, -1, 1, 1]),
})
output_string = self.decode(out)
input_list = self.decode_list(encoded_inputs)
output_list = self.decode_list(out)
return output_string, input_list, output_list, att_mats |
<SYSTEM_TASK:>
Shifts and pads with zero along an axis.
<END_TASK>
<USER_TASK:>
Description:
def shift_and_pad(tensor, shift, axis=0):
"""Shifts and pads with zero along an axis.
Example:
shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2]
shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0]
Args:
tensor: Tensor; to be shifted and padded.
shift: int; number of positions to shift by.
axis: int; along which axis to shift and pad.
Returns:
A Tensor with the same shape as the input tensor.
""" |
shape = tensor.shape
rank = len(shape)
assert 0 <= abs(axis) < rank
length = int(shape[axis])
assert 0 <= abs(shift) < length
paddings = [(0, 0)] * rank
begin = [0] * rank
size = [-1] * rank
if shift > 0:
paddings[axis] = (shift, 0)
size[axis] = length - shift
elif shift < 0:
paddings[axis] = (0, -shift)
begin[axis] = -shift
ret = tf.pad(tf.slice(tensor, begin, size), paddings)
return ret |
<SYSTEM_TASK:>
Given frame_logits from a per-pixel softmax, generate colors.
<END_TASK>
<USER_TASK:>
Description:
def pixels_from_softmax(frame_logits, pure_sampling=False,
temperature=1.0, gumbel_noise_factor=0.2):
"""Given frame_logits from a per-pixel softmax, generate colors.""" |
# If we're purely sampling, just sample each pixel.
if pure_sampling or temperature == 0.0:
return common_layers.sample_with_temperature(frame_logits, temperature)
# Gumbel-sample from the pixel sofmax and average by pixel values.
pixel_range = tf.to_float(tf.range(256))
for _ in range(len(frame_logits.get_shape().as_list()) - 1):
pixel_range = tf.expand_dims(pixel_range, axis=0)
frame_logits = tf.nn.log_softmax(frame_logits)
gumbel_samples = discretization.gumbel_sample(
common_layers.shape_list(frame_logits)) * gumbel_noise_factor
frame = tf.nn.softmax((frame_logits + gumbel_samples) / temperature, axis=-1)
result = tf.reduce_sum(frame * pixel_range, axis=-1)
# Round on the forward pass, not on the backward one.
return result + tf.stop_gradient(tf.round(result) - result) |
<SYSTEM_TASK:>
Removes top level TimeLimit Wrapper.
<END_TASK>
<USER_TASK:>
Description:
def remove_time_limit_wrapper(env):
"""Removes top level TimeLimit Wrapper.
Removes TimeLimit Wrapper from top level if exists, throws error if any other
TimeLimit Wrapper is present in stack.
Args:
env: environment
Returns:
the env with removed time limit wrapper.
""" |
if isinstance(env, gym.wrappers.TimeLimit):
env = env.env
env_ = env
while isinstance(env_, gym.Wrapper):
if isinstance(env_, gym.wrappers.TimeLimit):
raise ValueError("Can remove only top-level TimeLimit gym.Wrapper.")
env_ = env_.env
return env |
<SYSTEM_TASK:>
Wraps a gym environment. see make_gym_env for details.
<END_TASK>
<USER_TASK:>
Description:
def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env,
rendered_env_resize_to, sticky_actions):
"""Wraps a gym environment. see make_gym_env for details.""" |
# rl_env_max_episode_steps is None or int.
assert ((not rl_env_max_episode_steps) or
isinstance(rl_env_max_episode_steps, int))
wrap_with_time_limit = ((not rl_env_max_episode_steps) or
rl_env_max_episode_steps >= 0)
if wrap_with_time_limit:
env = remove_time_limit_wrapper(env)
if sticky_actions:
env = StickyActionEnv(env)
if maxskip_env:
env = MaxAndSkipEnv(env) # pylint: disable=redefined-variable-type
if rendered_env:
env = RenderedEnv(env, resize_to=rendered_env_resize_to)
if wrap_with_time_limit:
env = gym.wrappers.TimeLimit(
env, max_episode_steps=rl_env_max_episode_steps)
return env |
<SYSTEM_TASK:>
Create a gym env optionally with a time limit and maxskip wrapper.
<END_TASK>
<USER_TASK:>
Description:
def make_gym_env(name,
rl_env_max_episode_steps=-1,
maxskip_env=False,
rendered_env=False,
rendered_env_resize_to=None,
sticky_actions=False):
"""Create a gym env optionally with a time limit and maxskip wrapper.
NOTE: The returned env may already be wrapped with TimeLimit!
Args:
name: `str` - base name of the gym env to make.
rl_env_max_episode_steps: `int` or None - Using any value < 0 returns the
env as-in, otherwise we impose the requested timelimit. Setting this to
None returns a wrapped env that doesn't have a step limit.
maxskip_env: whether to also use MaxAndSkip wrapper before time limit.
rendered_env: whether to force render for observations. Use this for
environments that are not natively rendering the scene for observations.
rendered_env_resize_to: a list of [height, width] to change the original
resolution of the native environment render.
sticky_actions: whether to use sticky_actions before MaxAndSkip wrapper.
Returns:
An instance of `gym.Env` or `gym.Wrapper`.
""" |
env = gym.make(name)
return gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env,
rendered_env, rendered_env_resize_to, sticky_actions) |
<SYSTEM_TASK:>
Registers the class in Gym and returns the registered name and the env.
<END_TASK>
<USER_TASK:>
Description:
def register_gym_env(class_entry_point, version="v0", kwargs=None):
"""Registers the class in Gym and returns the registered name and the env.""" |
split_on_colon = class_entry_point.split(":")
assert len(split_on_colon) == 2
class_name = split_on_colon[1]
# We have to add the version to conform to gym's API.
env_name = "T2TEnv-{}-{}".format(class_name, version)
gym.envs.register(id=env_name, entry_point=class_entry_point, kwargs=kwargs)
tf.logging.info("Entry Point [%s] registered with id [%s]", class_entry_point,
env_name)
return env_name, gym.make(env_name) |
<SYSTEM_TASK:>
Repeat action, sum reward, and max over last observations.
<END_TASK>
<USER_TASK:>
Description:
def step(self, action):
"""Repeat action, sum reward, and max over last observations.""" |
total_reward = 0.0
done = None
for i in range(self._skip):
obs, reward, done, info = self.env.step(action)
if i == self._skip - 2:
self._obs_buffer[0] = obs
if i == self._skip - 1:
self._obs_buffer[1] = obs
total_reward += reward
if done:
break
# Note that the observation on the done=True frame doesn't matter.
max_frame = self._obs_buffer.max(axis=0)
return max_frame, total_reward, done, info |
<SYSTEM_TASK:>
Log out and possibly reraise errors during import.
<END_TASK>
<USER_TASK:>
Description:
def _handle_errors(errors):
"""Log out and possibly reraise errors during import.""" |
if not errors:
return
log_all = True # pylint: disable=unused-variable
err_msg = "T2T: skipped importing {num_missing} data_generators modules."
print(err_msg.format(num_missing=len(errors)))
for module, err in errors:
err_str = str(err)
if not _is_import_err_msg(err_str, module):
print("From module %s" % module)
raise err
if log_all:
print("Did not import module: %s; Cause: %s" % (module, err_str)) |
<SYSTEM_TASK:>
Create HParams with data_dir and problem hparams, if kwargs provided.
<END_TASK>
<USER_TASK:>
Description:
def create_hparams(hparams_set,
hparams_overrides_str="",
data_dir=None,
problem_name=None,
hparams_path=None):
"""Create HParams with data_dir and problem hparams, if kwargs provided.""" |
hparams = registry.hparams(hparams_set)
if hparams_path and tf.gfile.Exists(hparams_path):
hparams = create_hparams_from_json(hparams_path, hparams)
if data_dir:
hparams.add_hparam("data_dir", data_dir)
if hparams_overrides_str:
tf.logging.info("Overriding hparams in %s with %s", hparams_set,
hparams_overrides_str)
hparams = hparams.parse(hparams_overrides_str)
if problem_name:
add_problem_hparams(hparams, problem_name)
return hparams |
<SYSTEM_TASK:>
Loading hparams from json; can also start from hparams if specified.
<END_TASK>
<USER_TASK:>
Description:
def create_hparams_from_json(json_path, hparams=None):
"""Loading hparams from json; can also start from hparams if specified.""" |
tf.logging.info("Loading hparams from existing json %s" % json_path)
with tf.gfile.Open(json_path, "r") as f:
hparams_values = json.load(f)
# Prevent certain keys from overwriting the passed-in hparams.
# TODO(trandustin): Remove this hack after registries are available to avoid
# saving them as functions.
hparams_values.pop("bottom", None)
hparams_values.pop("loss", None)
hparams_values.pop("name", None)
hparams_values.pop("top", None)
hparams_values.pop("weights_fn", None)
new_hparams = hparam.HParams(**hparams_values)
# Some keys are in new_hparams but not hparams, so we need to be more
# careful than simply using parse_json() from HParams
if hparams: # hparams specified, so update values from json
for key in sorted(new_hparams.values().keys()):
if hasattr(hparams, key): # Overlapped keys
value = getattr(hparams, key)
new_value = getattr(new_hparams, key)
if value != new_value: # Different values
tf.logging.info("Overwrite key %s: %s -> %s" % (
key, value, new_value))
setattr(hparams, key, new_value)
else:
hparams = new_hparams
return hparams |
<SYSTEM_TASK:>
Add problem hparams for the problems.
<END_TASK>
<USER_TASK:>
Description:
def add_problem_hparams(hparams, problem_name_or_instance):
"""Add problem hparams for the problems.""" |
if isinstance(problem_name_or_instance, problem_lib.Problem):
problem = problem_name_or_instance
else:
problem = registry.problem(problem_name_or_instance)
p_hparams = problem.get_hparams(hparams)
hparams.problem = problem
hparams.problem_hparams = p_hparams |
<SYSTEM_TASK:>
Loads exampls from the tsv file.
<END_TASK>
<USER_TASK:>
Description:
def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01):
"""Loads exampls from the tsv file.
Args:
tmp_dir: temp directory.
prop_train: proportion of the train data
prop_val: proportion of the validation data
Returns:
All examples in the dataset pluse train, test, and development splits.
""" |
infile = generator_utils.maybe_download(tmp_dir, _TAR, _URL)
tf.logging.info('Loading examples')
all_examples = []
for i, d in enumerate(csv.DictReader(gzip.open(infile), delimiter='\t')):
if i % 100000 == 0:
tf.logging.info('%d examples have been loaded....' % i)
ex = {x: int(y) if y.isdigit() else y for x, y in d.items()}
all_examples.append(ex)
random.seed(1)
random.shuffle(all_examples)
n_train = int(len(all_examples) * prop_train)
n_val = n_train + int(len(all_examples) * prop_val)
train = all_examples[:n_train]
val = all_examples[n_train:n_val]
test = []
for e in all_examples[n_val:]:
if e['n_intervening'] == e['n_diff_intervening']:
test.append(e)
return all_examples, train, val, test |
<SYSTEM_TASK:>
Download and extract CIFAR to directory unless it is there.
<END_TASK>
<USER_TASK:>
Description:
def _get_cifar(directory, url):
"""Download and extract CIFAR to directory unless it is there.""" |
filename = os.path.basename(url)
path = generator_utils.maybe_download(directory, filename, url)
tarfile.open(path, "r:gz").extractall(directory) |
<SYSTEM_TASK:>
Image generator for CIFAR-10 and 100.
<END_TASK>
<USER_TASK:>
Description:
def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0):
"""Image generator for CIFAR-10 and 100.
Args:
cifar_version: string; one of "cifar10" or "cifar100"
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set, otherwise the test set.
how_many: how many images and labels to generate.
start_from: from which image to start.
Returns:
An instance of image_generator that produces CIFAR-10 images and labels.
""" |
if cifar_version == "cifar10":
url = _CIFAR10_URL
train_files = _CIFAR10_TRAIN_FILES
test_files = _CIFAR10_TEST_FILES
prefix = _CIFAR10_PREFIX
image_size = _CIFAR10_IMAGE_SIZE
label_key = "labels"
elif cifar_version == "cifar100" or cifar_version == "cifar20":
url = _CIFAR100_URL
train_files = _CIFAR100_TRAIN_FILES
test_files = _CIFAR100_TEST_FILES
prefix = _CIFAR100_PREFIX
image_size = _CIFAR100_IMAGE_SIZE
if cifar_version == "cifar100":
label_key = "fine_labels"
else:
label_key = "coarse_labels"
_get_cifar(tmp_dir, url)
data_files = train_files if training else test_files
all_images, all_labels = [], []
for filename in data_files:
path = os.path.join(tmp_dir, prefix, filename)
with tf.gfile.Open(path, "rb") as f:
if six.PY2:
data = cPickle.load(f)
else:
data = cPickle.load(f, encoding="latin1")
images = data["data"]
num_images = images.shape[0]
images = images.reshape((num_images, 3, image_size, image_size))
all_images.extend([
np.squeeze(images[j]).transpose((1, 2, 0)) for j in range(num_images)
])
labels = data[label_key]
all_labels.extend([labels[j] for j in range(num_images)])
return image_utils.image_generator(
all_images[start_from:start_from + how_many],
all_labels[start_from:start_from + how_many]) |
<SYSTEM_TASK:>
Base setting but quicker with only 2 epochs.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_ppo_quick():
"""Base setting but quicker with only 2 epochs.""" |
hparams = rlmb_ppo_base()
hparams.epochs = 2
hparams.model_train_steps = 25000
hparams.ppo_epochs_num = 700
hparams.ppo_epoch_length = 50
return hparams |
<SYSTEM_TASK:>
Base setting with a stochastic next-frame model.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_base_stochastic():
"""Base setting with a stochastic next-frame model.""" |
hparams = rlmb_base()
hparams.initial_epoch_train_steps_multiplier = 5
hparams.generative_model = "next_frame_basic_stochastic"
hparams.generative_model_params = "next_frame_basic_stochastic"
return hparams |
<SYSTEM_TASK:>
Long setting with stochastic discrete model & deterministic sim starts.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_long_stochastic_discrete_simulation_deterministic_starts():
"""Long setting with stochastic discrete model & deterministic sim starts.""" |
hparams = rlmb_base_stochastic_discrete()
hparams.generative_model_params = "next_frame_basic_stochastic_discrete_long"
hparams.ppo_epochs_num = 1000
hparams.simulation_random_starts = False
return hparams |
<SYSTEM_TASK:>
Base setting with sv2p as world model.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_base_sv2p():
"""Base setting with sv2p as world model.""" |
hparams = rlmb_base()
hparams.learning_rate_bump = 1.0
hparams.generative_model = "next_frame_sv2p"
hparams.generative_model_params = "next_frame_sv2p_atari"
return hparams |
<SYSTEM_TASK:>
Parameters to override for tiny setting excluding agent-related hparams.
<END_TASK>
<USER_TASK:>
Description:
def _rlmb_tiny_overrides():
"""Parameters to override for tiny setting excluding agent-related hparams.""" |
return dict(
epochs=1,
num_real_env_frames=128,
model_train_steps=2,
max_num_noops=1,
eval_max_num_noops=1,
generative_model_params="next_frame_tiny",
stop_loop_early=True,
resize_height_factor=2,
resize_width_factor=2,
wm_eval_rollout_ratios=[1],
rl_env_max_episode_steps=7,
eval_rl_env_max_episode_steps=7,
simulated_rollout_length=2,
eval_sampling_temps=[0.0, 1.0],
) |
<SYSTEM_TASK:>
Tiny setting with a stochastic next-frame model.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_tiny_stochastic():
"""Tiny setting with a stochastic next-frame model.""" |
hparams = rlmb_ppo_tiny()
hparams.epochs = 1 # Too slow with 2 for regular runs.
hparams.generative_model = "next_frame_basic_stochastic"
hparams.generative_model_params = "next_frame_basic_stochastic"
return hparams |
<SYSTEM_TASK:>
Tiny setting with a recurrent next-frame model.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_tiny_recurrent():
"""Tiny setting with a recurrent next-frame model.""" |
hparams = rlmb_ppo_tiny()
hparams.epochs = 1 # Too slow with 2 for regular runs.
hparams.generative_model = "next_frame_basic_recurrent"
hparams.generative_model_params = "next_frame_basic_recurrent"
return hparams |
<SYSTEM_TASK:>
Tiny setting with a tiny sv2p model.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_tiny_sv2p():
"""Tiny setting with a tiny sv2p model.""" |
hparams = rlmb_ppo_tiny()
hparams.generative_model = "next_frame_sv2p"
hparams.generative_model_params = "next_frame_sv2p_tiny"
hparams.grayscale = False
return hparams |
<SYSTEM_TASK:>
Grid over games and frames, and 5 runs each for variance.
<END_TASK>
<USER_TASK:>
Description:
def rlmb_grid(rhp):
"""Grid over games and frames, and 5 runs each for variance.""" |
rhp.set_categorical("loop.game", ["breakout", "pong", "freeway"])
base = 100000
medium = base // 2
small = medium // 2
rhp.set_discrete("loop.num_real_env_frames", [base, medium, small])
# Dummy parameter to get 5 runs for each configuration
rhp.set_discrete("model.moe_loss_coef", list(range(5))) |
<SYSTEM_TASK:>
Merge multiple HParams into one with scopes.
<END_TASK>
<USER_TASK:>
Description:
def merge_unscoped_hparams(scopes_and_hparams):
"""Merge multiple HParams into one with scopes.""" |
merged_values = {}
for (scope, hparams) in scopes_and_hparams:
for key, value in six.iteritems(hparams.values()):
scoped_key = "%s.%s" % (scope, key)
merged_values[scoped_key] = value
return hparam.HParams(**merged_values) |
<SYSTEM_TASK:>
Split single HParams with scoped keys into multiple.
<END_TASK>
<USER_TASK:>
Description:
def split_scoped_hparams(scopes, merged_hparams):
"""Split single HParams with scoped keys into multiple.""" |
split_values = {scope: {} for scope in scopes}
merged_values = merged_hparams.values()
for scoped_key, value in six.iteritems(merged_values):
scope = scoped_key.split(".")[0]
key = scoped_key[len(scope) + 1:]
split_values[scope][key] = value
return [
hparam.HParams(**split_values[scope]) for scope in scopes
] |
<SYSTEM_TASK:>
Create HParams suitable for training loop from scoped HParams.
<END_TASK>
<USER_TASK:>
Description:
def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id):
"""Create HParams suitable for training loop from scoped HParams.
Args:
scoped_overrides: HParams, with keys all scoped by one of HP_SCOPES. These
parameters are overrides for the base HParams created by
create_loop_hparams.
trial_id: str, trial identifier. This is used to register unique HParams
names for the underlying model and ppo HParams.
Returns:
HParams suitable for passing to training_loop.
""" |
trial_hp_overrides = scoped_overrides.values()
# Create loop, model, and ppo base HParams
loop_hp = create_loop_hparams()
model_hp_name = trial_hp_overrides.get(
"loop.generative_model_params", loop_hp.generative_model_params)
model_hp = registry.hparams(model_hp_name).parse(FLAGS.hparams)
base_algo_params_name = trial_hp_overrides.get(
"loop.base_algo_params", loop_hp.base_algo_params)
algo_hp = registry.hparams(base_algo_params_name)
# Merge them and then override with the scoped overrides
combined_hp = merge_unscoped_hparams(
zip(HP_SCOPES, [loop_hp, model_hp, algo_hp]))
combined_hp.override_from_dict(trial_hp_overrides)
# Split out the component hparams
loop_hp, model_hp, algo_hp = (
split_scoped_hparams(HP_SCOPES, combined_hp))
# Dynamic register the model hp and set the new name in loop_hp
model_hp_name = "model_hp_%s" % str(trial_id)
dynamic_register_hparams(model_hp_name, model_hp)
loop_hp.generative_model_params = model_hp_name
# Dynamic register the algo hp and set the new name in loop_hp
algo_hp_name = "algo_hp_%s" % str(trial_id)
dynamic_register_hparams(algo_hp_name, algo_hp)
loop_hp.base_algo_params = algo_hp_name
return loop_hp |
<SYSTEM_TASK:>
Get mapping from keyboard keys to actions.
<END_TASK>
<USER_TASK:>
Description:
def get_keys_to_action(self):
"""Get mapping from keyboard keys to actions.
Required by gym.utils.play in environment or top level wrapper.
Returns:
{
Unicode code point for keyboard key: action (formatted for step()),
...
}
""" |
# Based on gym AtariEnv.get_keys_to_action()
keyword_to_key = {
"UP": ord("w"),
"DOWN": ord("s"),
"LEFT": ord("a"),
"RIGHT": ord("d"),
"FIRE": ord(" "),
}
keys_to_action = {}
for action_id, action_meaning in enumerate(self.action_meanings):
keys_tuple = tuple(sorted([
key for keyword, key in keyword_to_key.items()
if keyword in action_meaning]))
assert keys_tuple not in keys_to_action
keys_to_action[keys_tuple] = action_id
# Special actions:
keys_to_action[(ord("r"),)] = self.RETURN_DONE_ACTION
keys_to_action[(ord("c"),)] = self.TOGGLE_WAIT_ACTION
keys_to_action[(ord("n"),)] = self.WAIT_MODE_NOOP_ACTION
return keys_to_action |
<SYSTEM_TASK:>
Construct observation, return usual step tuple.
<END_TASK>
<USER_TASK:>
Description:
def _player_step_tuple(self, envs_step_tuples):
"""Construct observation, return usual step tuple.
Args:
envs_step_tuples: tuples.
Returns:
Step tuple: ob, reward, done, info
ob: concatenated images [simulated observation, real observation,
difference], with additional informations in header.
reward: real environment reward
done: True iff. envs_step_tuples['real_env'][2] is True
info: real environment info
""" |
ob_real, reward_real, _, _ = envs_step_tuples["real_env"]
ob_sim, reward_sim, _, _ = envs_step_tuples["sim_env"]
ob_err = absolute_hinge_difference(ob_sim, ob_real)
ob_real_aug = self._augment_observation(ob_real, reward_real,
self.cumulative_real_reward)
ob_sim_aug = self._augment_observation(ob_sim, reward_sim,
self.cumulative_sim_reward)
ob_err_aug = self._augment_observation(
ob_err, reward_sim - reward_real,
self.cumulative_sim_reward - self.cumulative_real_reward
)
ob = np.concatenate([ob_sim_aug, ob_real_aug, ob_err_aug], axis=1)
_, reward, done, info = envs_step_tuples["real_env"]
return ob, reward, done, info |
<SYSTEM_TASK:>
Reset simulated and real environments.
<END_TASK>
<USER_TASK:>
Description:
def reset(self):
"""Reset simulated and real environments.""" |
self._frame_counter = 0
ob_real = self.real_env.reset()
# Initialize simulated environment with frames from real one.
self.sim_env.add_to_initial_stack(ob_real)
for _ in range(3):
ob_real, _, _, _ = self.real_env.step(self.name_to_action_num["NOOP"])
self.sim_env.add_to_initial_stack(ob_real)
ob_sim = self.sim_env.reset()
assert np.all(ob_real == ob_sim)
self._last_step_tuples = self._pack_step_tuples((ob_real, 0, False, {}),
(ob_sim, 0, False, {}))
self.set_zero_cumulative_rewards()
ob, _, _, _ = self._player_step_tuple(self._last_step_tuples)
return ob |
<SYSTEM_TASK:>
Compute time first and second-order derivative channels.
<END_TASK>
<USER_TASK:>
Description:
def add_delta_deltas(filterbanks, name=None):
"""Compute time first and second-order derivative channels.
Args:
filterbanks: float32 tensor with shape [batch_size, len, num_bins, 1]
name: scope name
Returns:
float32 tensor with shape [batch_size, len, num_bins, 3]
""" |
delta_filter = np.array([2, 1, 0, -1, -2])
delta_delta_filter = scipy.signal.convolve(delta_filter, delta_filter, "full")
delta_filter_stack = np.array(
[[0] * 4 + [1] + [0] * 4, [0] * 2 + list(delta_filter) + [0] * 2,
list(delta_delta_filter)],
dtype=np.float32).T[:, None, None, :]
delta_filter_stack /= np.sqrt(
np.sum(delta_filter_stack**2, axis=0, keepdims=True))
filterbanks = tf.nn.conv2d(
filterbanks, delta_filter_stack, [1, 1, 1, 1], "SAME", data_format="NHWC",
name=name)
return filterbanks |
<SYSTEM_TASK:>
Implement mel-filterbank extraction using tf ops.
<END_TASK>
<USER_TASK:>
Description:
def compute_mel_filterbank_features(
waveforms,
sample_rate=16000, dither=1.0 / np.iinfo(np.int16).max, preemphasis=0.97,
frame_length=25, frame_step=10, fft_length=None,
window_fn=functools.partial(tf.contrib.signal.hann_window, periodic=True),
lower_edge_hertz=80.0, upper_edge_hertz=7600.0, num_mel_bins=80,
log_noise_floor=1e-3, apply_mask=True):
"""Implement mel-filterbank extraction using tf ops.
Args:
waveforms: float32 tensor with shape [batch_size, max_len]
sample_rate: sampling rate of the waveform
dither: stddev of Gaussian noise added to waveform to prevent quantization
artefacts
preemphasis: waveform high-pass filtering constant
frame_length: frame length in ms
frame_step: frame_Step in ms
fft_length: number of fft bins
window_fn: windowing function
lower_edge_hertz: lowest frequency of the filterbank
upper_edge_hertz: highest frequency of the filterbank
num_mel_bins: filterbank size
log_noise_floor: clip small values to prevent numeric overflow in log
apply_mask: When working on a batch of samples, set padding frames to zero
Returns:
filterbanks: a float32 tensor with shape [batch_size, len, num_bins, 1]
""" |
# `stfts` is a complex64 Tensor representing the short-time Fourier
# Transform of each signal in `signals`. Its shape is
# [batch_size, ?, fft_unique_bins]
# where fft_unique_bins = fft_length // 2 + 1
# Find the wave length: the largest index for which the value is !=0
# note that waveforms samples that are exactly 0.0 are quite common, so
# simply doing sum(waveforms != 0, axis=-1) will not work correctly.
wav_lens = tf.reduce_max(
tf.expand_dims(tf.range(tf.shape(waveforms)[1]), 0) *
tf.to_int32(tf.not_equal(waveforms, 0.0)),
axis=-1) + 1
if dither > 0:
waveforms += tf.random_normal(tf.shape(waveforms), stddev=dither)
if preemphasis > 0:
waveforms = waveforms[:, 1:] - preemphasis * waveforms[:, :-1]
wav_lens -= 1
frame_length = int(frame_length * sample_rate / 1e3)
frame_step = int(frame_step * sample_rate / 1e3)
if fft_length is None:
fft_length = int(2**(np.ceil(np.log2(frame_length))))
stfts = tf.contrib.signal.stft(
waveforms,
frame_length=frame_length,
frame_step=frame_step,
fft_length=fft_length,
window_fn=window_fn,
pad_end=True)
stft_lens = (wav_lens + (frame_step - 1)) // frame_step
masks = tf.to_float(tf.less_equal(
tf.expand_dims(tf.range(tf.shape(stfts)[1]), 0),
tf.expand_dims(stft_lens, 1)))
# An energy spectrogram is the magnitude of the complex-valued STFT.
# A float32 Tensor of shape [batch_size, ?, 257].
magnitude_spectrograms = tf.abs(stfts)
# Warp the linear-scale, magnitude spectrograms into the mel-scale.
num_spectrogram_bins = magnitude_spectrograms.shape[-1].value
linear_to_mel_weight_matrix = (
tf.contrib.signal.linear_to_mel_weight_matrix(
num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz,
upper_edge_hertz))
mel_spectrograms = tf.tensordot(
magnitude_spectrograms, linear_to_mel_weight_matrix, 1)
# Note: Shape inference for tensordot does not currently handle this case.
mel_spectrograms.set_shape(magnitude_spectrograms.shape[:-1].concatenate(
linear_to_mel_weight_matrix.shape[-1:]))
log_mel_sgram = tf.log(tf.maximum(log_noise_floor, mel_spectrograms))
if apply_mask:
log_mel_sgram *= tf.expand_dims(tf.to_float(masks), -1)
return tf.expand_dims(log_mel_sgram, -1, name="mel_sgrams") |
<SYSTEM_TASK:>
Plays the env problem by randomly sampling actions for `num_steps`.
<END_TASK>
<USER_TASK:>
Description:
def play_env_problem_randomly(env_problem,
num_steps):
"""Plays the env problem by randomly sampling actions for `num_steps`.""" |
# Reset all environments.
env_problem.reset()
# Play all environments, sampling random actions each time.
for _ in range(num_steps):
# Sample batch_size actions from the action space and stack them.
actions = np.stack([env_problem.action_space.sample() for _ in range(
env_problem.batch_size)])
# Execute actions, observations are stored in `env_problem`.
_, _, dones, _ = env_problem.step(actions)
# Get the indices where we are done and reset those.
env_problem.reset(indices=done_indices(dones)) |
<SYSTEM_TASK:>
Generates samples of text from the provided vocabulary.
<END_TASK>
<USER_TASK:>
Description:
def generate_plaintext_random(plain_vocab, distribution, train_samples,
length):
"""Generates samples of text from the provided vocabulary.
Args:
plain_vocab: vocabulary.
distribution: distribution.
train_samples: samples for training.
length: length.
Returns:
train_indices (np.array of Integers): random integers for training.
shape = [num_samples, length]
test_indices (np.array of Integers): random integers for testing.
shape = [num_samples, length]
plain_vocab (list of Integers): unique vocabularies.
""" |
if distribution is not None:
assert len(distribution) == len(plain_vocab)
train_indices = np.random.choice(
range(len(plain_vocab)), (train_samples, length), p=distribution)
return train_indices |
<SYSTEM_TASK:>
Encrypt plain text with a single shift layer.
<END_TASK>
<USER_TASK:>
Description:
def encipher_shift(plaintext, plain_vocab, shift):
"""Encrypt plain text with a single shift layer.
Args:
plaintext (list of list of Strings): a list of plain text to encrypt.
plain_vocab (list of Integer): unique vocabularies being used.
shift (Integer): number of shift, shift to the right if shift is positive.
Returns:
ciphertext (list of Strings): encrypted plain text.
""" |
ciphertext = []
cipher = ShiftEncryptionLayer(plain_vocab, shift)
for _, sentence in enumerate(plaintext):
cipher_sentence = []
for _, character in enumerate(sentence):
encrypted_char = cipher.encrypt_character(character)
cipher_sentence.append(encrypted_char)
ciphertext.append(cipher_sentence)
return ciphertext |
<SYSTEM_TASK:>
Encrypt plain text with given key.
<END_TASK>
<USER_TASK:>
Description:
def encipher_vigenere(plaintext, plain_vocab, key):
"""Encrypt plain text with given key.
Args:
plaintext (list of list of Strings): a list of plain text to encrypt.
plain_vocab (list of Integer): unique vocabularies being used.
key (list of Integer): key to encrypt cipher using Vigenere table.
Returns:
ciphertext (list of Strings): encrypted plain text.
""" |
ciphertext = []
# generate Vigenere table
layers = [
ShiftEncryptionLayer(plain_vocab, i) for i in range(len(plain_vocab))
]
for i, sentence in enumerate(plaintext):
cipher_sentence = []
for j, character in enumerate(sentence):
key_idx = key[j % len(key)]
encrypted_char = layers[key_idx].encrypt_character(character)
cipher_sentence.append(encrypted_char)
ciphertext.append(cipher_sentence)
return ciphertext |
<SYSTEM_TASK:>
Add mixture of experts with ~1B params.
<END_TASK>
<USER_TASK:>
Description:
def super_lm_moe():
"""Add mixture of experts with ~1B params.""" |
hparams = super_lm_base()
hparams.layers = (
("n,att,m,d,a," "n,moe,m,d,a,") * 4 + "n,ffn,d")
hparams.moe_num_experts = 32
hparams.moe_hidden_sizes = "1024"
return hparams |
<SYSTEM_TASK:>
Series of architectural experiments on Translation.
<END_TASK>
<USER_TASK:>
Description:
def xmoe_tr_dense_2k():
"""Series of architectural experiments on Translation.
# run on 8-core setup
119M params, einsum=0.95e13
Returns:
a hparams
""" |
hparams = mtf_transformer2.mtf_bitransformer_base()
hparams.encoder_layers = ["self_att", "drd"] * 4
hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 4
hparams.batch_size = 64
hparams.shared_embedding_and_softmax_weights = True
hparams.mesh_shape = "batch:8"
return hparams |
<SYSTEM_TASK:>
Series of architectural experiments on cheap language models.
<END_TASK>
<USER_TASK:>
Description:
def xmoe_dense_4k():
"""Series of architectural experiments on cheap language models.
For all of these architectures, we run on languagemodel_lm1b8k_packed
for 32000 steps.
All log-perplexities are per-token - multiply by 1.298 for per-word
Results:
model params(M) einsum alltoall mxu-util log-ppl
xmoe_dense_4k 30 3.0e12 0 45% 3.31
xmoe_dense_8k 46 4.7e12 0 49% 3.24
xmoe_dense_64k 282 2.8e13 0 3.06
xmoe_top_2 282 4.0e12 3.4e8 36% 3.07
xmoe_top_2_c15 282 4.5e12 4.0e8 38% 3.07
xmoe_2d 282 5.3e12 7.6e8 34% 3.06
Trained at 4x the batch size:
xmoe_2d_88 1090 2.1e13 3.0e9 24% 3.07
Note: configurations and code are likely to change without notice.
Returns:
a hparams
""" |
hparams = mtf_transformer.mtf_transformer_base_lm()
hparams.attention_dropout = 0.0
hparams.relu_dropout = 0.0
hparams.layer_prepostprocess_dropout = 0.0
# The following hparams are constant across all these experiments.
hparams.batch_size = 128
hparams.d_model = 512
hparams.d_kv = 128
hparams.num_heads = 4
hparams.decoder_layers = ["att", "drd"] * 4
hparams.shared_embedding_and_softmax_weights = False
hparams.learning_rate_schedule = "rsqrt_decay"
# We will vary the following parameters related to the ffn/moe layers.
hparams.d_ff = 4096
hparams.layout = "batch:batch;vocab:model;d_ff:model;heads:model"
hparams.mesh_shape = "batch:8"
return hparams |
<SYSTEM_TASK:>
Two-dimensional hierarchical mixture of 16 experts.
<END_TASK>
<USER_TASK:>
Description:
def xmoe_2d():
"""Two-dimensional hierarchical mixture of 16 experts.""" |
hparams = xmoe_top_2()
hparams.decoder_layers = ["att", "hmoe"] * 4
hparams.mesh_shape = "b0:2;b1:4"
hparams.outer_batch_size = 4
hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0"
hparams.moe_num_experts = [4, 4]
return hparams |
<SYSTEM_TASK:>
Series of architectural experiments on language modeling.
<END_TASK>
<USER_TASK:>
Description:
def xmoe2_dense(sz):
"""Series of architectural experiments on language modeling.
Larger models than the ones above.
All models are trained on sequences of 1024 tokens.
We assume infinite training data, so no dropout necessary.
We process 2^36 tokens in training = 524288 steps at batch size 128
TODO(noam): find a large enough dataset for these experiments.
You can use languagemodel_wiki_noref_v32k_l1k, but this is too small,
(1 epoch = ~46000 steps) so training will cover about 11 epochs.
Note: configurations and code are likely to change without notice.
Run on TPU 4x4 for 524288 steps unless otherwise indicated.
Args:
sz: an integer
Returns:
a hparams
""" |
hparams = mtf_transformer.mtf_transformer_paper_lm(sz)
hparams.attention_dropout = 0.0
hparams.relu_dropout = 0.0
hparams.layer_prepostprocess_dropout = 0.0
hparams.max_length = 1024
hparams.batch_size = 128
hparams.learning_rate_schedule = "rsqrt_decay*linear_decay"
hparams.learning_rate_decay_steps = 65536
hparams.layout = "batch:batch;vocab:model;d_ff:model;heads:model"
hparams.mesh_shape = "batch:32"
return hparams |
<SYSTEM_TASK:>
Model incorporating mixture-of-experts and local-attention.
<END_TASK>
<USER_TASK:>
Description:
def xmoe2_v1():
"""Model incorporating mixture-of-experts and local-attention.
~6B parameters
32 experts in 3 hierarchichal moe layers.
Returns:
a hparams
""" |
hparams = xmoe2_dense(0)
moe.set_default_moe_hparams(hparams)
hparams.decoder_layers = (
["local_att", "local_att", "drd",
"att", "drd", "local_att", "local_att", "hmoe"] * 4)[:-1]
hparams.d_ff = 2048
hparams.d_kv = 128
hparams.moe_hidden_size = 32768
hparams.mesh_shape = "b0:4;b1:8"
hparams.layout = "outer_batch:b0;inner_batch:b1,expert_x:b1,expert_y:b0"
hparams.outer_batch_size = 4
hparams.moe_num_experts = [8, 4]
hparams.num_heads = 4
return hparams |
<SYSTEM_TASK:>
Set of architectural experiments - language model on wikipedia on a 2x2.
<END_TASK>
<USER_TASK:>
Description:
def wiki_2x2_base():
"""Set of architectural experiments - language model on wikipedia on a 2x2.
1 epoch = ~180k steps at batch size 32 - we may never finish an epoch!
Returns:
a hparams
""" |
hparams = mtf_transformer.mtf_transformer_base_lm()
hparams.shared_embedding_and_softmax_weights = False
# no dropout - dataset is big enough to avoid overfitting.
hparams.attention_dropout = 0.0
hparams.relu_dropout = 0.0
hparams.layer_prepostprocess_dropout = 0.0
hparams.max_length = 1024
# 4 sequences per core
hparams.batch_size = 32
# We don't use linear decay in these experiments, since we don't want
# a sharp jump in quality at the end of the training schedule.
# You can insert this once you find the right architecture.
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.mesh_shape = "all:8"
hparams.layout = "batch:all;experts:all"
# parameters for mixture-of-experts
moe.set_default_moe_hparams(hparams)
hparams.moe_num_experts = 16
hparams.moe_hidden_size = 8192
hparams.decoder_layers = ["att", "drd"] * 6
hparams.d_model = 1024
hparams.d_ff = 2048
hparams.d_kv = 128
hparams.num_heads = 4
return hparams |
<SYSTEM_TASK:>
Replace tokens instead of masking.
<END_TASK>
<USER_TASK:>
Description:
def denoise_z15():
"""Replace tokens instead of masking.""" |
hparams = xmoe2_dense_0()
hparams.decoder_type = "denoising"
hparams.noising_spec_train = {"type": "random_zipfian", "prob": 0.15}
hparams.noising_use_eval_during_train = 0.25
return hparams |
<SYSTEM_TASK:>
Get a Counter with the ngrams of the given ID list.
<END_TASK>
<USER_TASK:>
Description:
def _get_ngram_counter(ids, n):
"""Get a Counter with the ngrams of the given ID list.
Args:
ids: np.array or a list corresponding to a single sentence
n: n-gram size
Returns:
collections.Counter with ID tuples as keys and 1s as values.
""" |
# Remove zero IDs used to pad the sequence.
ids = [token_id for token_id in ids if token_id != 0]
ngram_list = [tuple(ids[i:i + n]) for i in range(len(ids) + 1 - n)]
ngrams = set(ngram_list)
counts = collections.Counter()
for ngram in ngrams:
counts[ngram] = 1
return counts |
<SYSTEM_TASK:>
Compute Fbeta score.
<END_TASK>
<USER_TASK:>
Description:
def _get_fbeta_score(true_positives, selected, relevant, beta=1):
"""Compute Fbeta score.
Args:
true_positives: Number of true positive ngrams.
selected: Number of selected ngrams.
relevant: Number of relevant ngrams.
beta: 0 gives precision only, 1 gives F1 score, and Inf gives recall only.
Returns:
Fbeta score.
""" |
precision = 1
if selected > 0:
precision = true_positives / selected
if beta == 0:
return precision
recall = 1
if relevant > 0:
recall = true_positives / relevant
if precision > 0 and recall > 0:
beta2 = beta * beta
return (1 + beta2) * precision * recall / (beta2 * precision + recall)
else:
return 0 |
<SYSTEM_TASK:>
Compute the SARI score for a single prediction and one or more targets.
<END_TASK>
<USER_TASK:>
Description:
def get_sari_score(source_ids, prediction_ids, list_of_targets,
max_gram_size=4, beta_for_deletion=0):
"""Compute the SARI score for a single prediction and one or more targets.
Args:
source_ids: a list / np.array of SentencePiece IDs
prediction_ids: a list / np.array of SentencePiece IDs
list_of_targets: a list of target ID lists / np.arrays
max_gram_size: int. largest n-gram size we care about (e.g. 3 for unigrams,
bigrams, and trigrams)
beta_for_deletion: beta for deletion F score.
Returns:
the SARI score and its three components: add, keep, and deletion scores
""" |
addition_scores = []
keep_scores = []
deletion_scores = []
for n in range(1, max_gram_size + 1):
source_counts = _get_ngram_counter(source_ids, n)
prediction_counts = _get_ngram_counter(prediction_ids, n)
# All ngrams in the targets with count 1.
target_counts = collections.Counter()
# All ngrams in the targets with count r/num_targets, where r is the number
# of targets where the ngram occurs.
weighted_target_counts = collections.Counter()
num_nonempty_targets = 0
for target_ids_i in list_of_targets:
target_counts_i = _get_ngram_counter(target_ids_i, n)
if target_counts_i:
weighted_target_counts += target_counts_i
num_nonempty_targets += 1
for gram in weighted_target_counts.keys():
weighted_target_counts[gram] /= num_nonempty_targets
target_counts[gram] = 1
keep_scores.append(get_keep_score(source_counts, prediction_counts,
weighted_target_counts))
deletion_scores.append(get_deletion_score(source_counts, prediction_counts,
weighted_target_counts,
beta_for_deletion))
addition_scores.append(get_addition_score(source_counts, prediction_counts,
target_counts))
avg_keep_score = sum(keep_scores) / max_gram_size
avg_addition_score = sum(addition_scores) / max_gram_size
avg_deletion_score = sum(deletion_scores) / max_gram_size
sari = (avg_keep_score + avg_addition_score + avg_deletion_score) / 3.0
return sari, avg_keep_score, avg_addition_score, avg_deletion_score |
<SYSTEM_TASK:>
Download all MNIST files to directory unless they are there.
<END_TASK>
<USER_TASK:>
Description:
def _get_mnist(directory):
"""Download all MNIST files to directory unless they are there.""" |
for filename in [
_MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME,
_MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME
]:
generator_utils.maybe_download(directory, filename, _MNIST_URL + filename) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.