Code
stringlengths 103
85.9k
| Summary
sequencelengths 0
94
|
---|---|
Please provide a description of the function:def maybe_download_image_dataset(image_ids, target_dir):
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) | [
"Download a set of images from api.brain-map.org to `target_dir`.\n\n Args:\n image_ids: list, a list of image ids.\n target_dir: str, a directory to which to download the images.\n "
] |
Please provide a description of the function:def random_square_mask(shape, fraction):
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 | [
"Create a numpy array with specified shape and masked fraction.\n\n Args:\n shape: tuple, shape of the mask to create.\n fraction: float, fraction of the mask area to populate with `mask_scalar`.\n\n Returns:\n numpy.array: A numpy array storing the mask.\n "
] |
Please provide a description of the function:def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE,
training_fraction=0.95):
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]
} | [
"Base problem example generator for Allen Brain Atlas problems.\n\n Args:\n\n tmp_dir: str, a directory where raw example input data has been stored.\n training: bool, whether the mode of operation is training (or,\n alternatively, evaluation), determining whether examples in tmp_dir\n prefixed with train or dev will be used.\n size: int, the image size to add to the example annotation.\n training_fraction: float, the fraction of the sub-image path list to\n consider as the basis for training examples.\n\n Yields:\n A dictionary representing the images with the following fields:\n * image/encoded: The string encoding the image as JPEG.\n * image/format: The string \"jpeg\" indicating the image format.\n * image/height: The integer indicating the image height.\n * image/width: The integer indicating the image height.\n\n "
] |
Please provide a description of the function:def transformer_moe_base():
hparams = common_hparams.basic_params1()
hparams.norm_type = "layer"
hparams.hidden_size = 512
hparams.batch_size = 4096
hparams.max_length = 2001
hparams.max_input_seq_length = 2000
hparams.max_target_seq_length = 2000
hparams.dropout = 0.0
hparams.clip_grad_norm = 0. # i.e. no gradient clipping
hparams.optimizer_adam_epsilon = 1e-9
hparams.learning_rate_decay_scheme = "noam"
hparams.learning_rate = 0.1
hparams.learning_rate_warmup_steps = 2000
hparams.initializer_gain = 1.0
hparams.num_hidden_layers = 5
hparams.initializer = "uniform_unit_scaling"
hparams.weight_decay = 0.0
hparams.optimizer_adam_beta1 = 0.9
hparams.optimizer_adam_beta2 = 0.98
hparams.num_sampled_classes = 0
hparams.label_smoothing = 0.0
hparams.shared_embedding_and_softmax_weights = True
# According to noam, ("n", "da") seems better for harder-to-learn models
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# Hparams used by transformer_prepare_decoder() function
hparams.add_hparam("pos", "timing") # timing, none
hparams.add_hparam("proximity_bias", False)
hparams.add_hparam("causal_decoder_self_attention", True)
hparams = common_attention.add_standard_attention_hparams(hparams)
# Decoder layers type. If set, num_decoder_layers parameter will be ignored
# and the number of decoder layer will be deduced from the string
# See top file comment for example of usage
hparams.add_hparam("layer_types", "")
# Default attention type (ex: a, loc, red,...) and feed-forward type (ex: fc,
# sep, moe,...)
hparams.add_hparam("default_att", "a")
hparams.add_hparam("default_ff", "fc")
return hparams | [
"Set of hyperparameters."
] |
Please provide a description of the function:def transformer_moe_8k():
hparams = transformer_moe_base()
hparams.batch_size = 8192
hparams.max_length = 0 # max_length == batch_size
hparams.eval_drop_long_sequences = True
hparams.min_length_bucket = 256 # Avoid cyclic problems for big batches
hparams.default_ff = "sep"
hparams.hidden_size = 1024
return hparams | [
"Hyper parameters specifics for long sequence generation."
] |
Please provide a description of the function:def transformer_moe_2k():
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 | [
"Base transformers model with moe.\n\n Will have the following architecture:\n * No encoder.\n * Layer 0: a - sep (self-attention - unmasked separable convolutions)\n * Layer 1: a - sep\n * Layer 2: a - sep\n * Layer 3: a - sep\n * Layer 4: a - sep\n * Decoder architecture:\n * Layer 0: a - a - sepm (self-attention - enco/deco-attention - masked sep)\n * Layer 1: a - a - sepm\n * Layer 2: a - a - moe (mixture of expert layers in the middle)\n * Layer 3: a - a - sepm\n * Layer 4: a - a - sepm\n\n Returns:\n hparams\n "
] |
Please provide a description of the function:def transformer_moe_prepend_8k():
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 | [
"Model which formulate a seq2seq problem as language modeling."
] |
Please provide a description of the function:def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1,
training=True, bottleneck=True, padding='SAME'):
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 | [
"Applies residual function for RevNet.\n\n Args:\n x: input tensor\n depth1: Number of output channels for the first and second conv layers.\n depth2: Number of output channels for the third conv layer.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n first_batch_norm: Whether to keep the first batch norm layer or not.\n Typically used in the first RevNet block.\n stride: Stride for the first conv filter. Note that this particular\n RevNet architecture only varies the stride for the first conv\n filter. The stride for the second conv filter is always set to 1.\n training: True for train phase, False for eval phase.\n bottleneck: If true, apply bottleneck 1x1 down/up sampling.\n padding: Padding for each conv layer.\n\n Returns:\n Output tensor after applying residual function for RevNet.\n "
] |
Please provide a description of the function:def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'):
conv = CONFIG[dim]['conv']
with tf.variable_scope(scope):
x = conv(x, output_channels, 1, strides=stride, padding='SAME',
activation=None)
return x | [
"Downsamples 'x' by `stride` using a 1x1 convolution filter.\n\n Args:\n x: input tensor of size [N, H, W, C]\n output_channels: Desired number of output channels.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n stride: What stride to use. Usually 1 or 2.\n scope: Optional variable scope.\n\n Returns:\n A downsampled tensor of size [N, H/2, W/2, output_channels] if stride\n is 2, else returns a tensor of size [N, H, W, output_channels] if\n stride is 1.\n "
] |
Please provide a description of the function:def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'):
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 | [
"Downsamples 'x' by `stride` using average pooling.\n\n Args:\n x: input tensor of size [N, H, W, C]\n output_channels: Desired number of output channels.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n stride: What stride to use. Usually 1 or 2.\n scope: Optional variable scope.\n\n Returns:\n A downsampled tensor of size [N, H/2, W/2, output_channels] if stride\n is 2, else returns a tensor of size [N, H, W, output_channels] if\n stride is 1.\n "
] |
Please provide a description of the function:def init(images, num_channels, dim='2d', stride=2,
kernel_size=7, maxpool=True, training=True, scope='init'):
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 | [
"Standard ResNet initial block used as first RevNet block.\n\n Args:\n images: [N, H, W, 3] tensor of input images to the model.\n num_channels: Output depth of convolutional layer in initial block.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n stride: stride for the convolution and pool layer.\n kernel_size: Size of the initial convolution filter\n maxpool: If true, apply a maxpool after the convolution\n training: True for train phase, False for eval phase.\n scope: Optional scope for the init block.\n\n Returns:\n Two [N, H, W, C] output activations from input images.\n "
] |
Please provide a description of the function:def unit(x1, x2, block_num, depth, num_layers, dim='2d',
bottleneck=True, first_batch_norm=True, stride=1, training=True):
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 | [
"Implements bottleneck RevNet unit from authors' RevNet architecture.\n\n Args:\n x1: [N, H, W, C] tensor of network activations.\n x2: [N, H, W, C] tensor of network activations.\n block_num: integer ID of block\n depth: First depth in bottleneck residual unit.\n num_layers: Number of layers in the RevNet block.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n bottleneck: Should a bottleneck layer be used.\n first_batch_norm: Whether to keep the first batch norm layer or not.\n Typically used in the first RevNet block.\n stride: Stride for the residual function.\n training: True for train phase, False for eval phase.\n\n Returns:\n Two [N, H, W, C] output activation tensors.\n "
] |
Please provide a description of the function:def final_block(x1, x2, dim='2d', training=True, scope='final_block'):
# 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 | [
"Converts activations from last RevNet block to pre-logits.\n\n Args:\n x1: [NxHxWxC] tensor of network activations.\n x2: [NxHxWxC] tensor of network activations.\n dim: '2d' if 2-dimensional, '3d' if 3-dimensional.\n training: True for train phase, False for eval phase.\n scope: Optional variable scope for the final block.\n\n Returns:\n [N, hidden_dim] pre-logits tensor from activations x1 and x2.\n "
] |
Please provide a description of the function:def revnet(inputs, hparams, reuse=None):
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 | [
"Uses Tensor2Tensor memory optimized RevNet block to build a RevNet.\n\n Args:\n inputs: [NxHxWx3] tensor of input images to the model.\n hparams: HParams object that contains the following parameters,\n in addition to the parameters contained in the basic_params1() object in\n the common_hparams module:\n num_channels_first - A Python list where each element represents the\n depth of the first and third convolutional layers in the bottleneck\n residual unit for a given block.\n num_channels_second - A Python list where each element represents the\n depth of the second convolutional layer in the bottleneck residual\n unit for a given block.\n num_layers_per_block - A Python list containing the number of RevNet\n layers for each block.\n first_batch_norm - A Python list containing booleans representing the\n presence of a batch norm layer at the beginning of a given block.\n strides - A Python list containing integers representing the stride of\n the residual function for each block.\n num_channels_init_block - An integer representing the number of channels\n for the convolutional layer in the initial block.\n dimension - A string (either \"2d\" or \"3d\") that decides if the RevNet is\n 2-dimensional or 3-dimensional.\n reuse: Whether to reuse the default variable scope.\n\n Returns:\n [batch_size, hidden_dim] pre-logits tensor from the bottleneck RevNet.\n "
] |
Please provide a description of the function:def revnet_base():
hparams = common_hparams.basic_params1()
hparams.add_hparam('num_channels', [64, 128, 256, 416])
hparams.add_hparam('num_layers_per_block', [1, 1, 10, 1])
hparams.add_hparam('bottleneck', True)
hparams.add_hparam('first_batch_norm', [False, True, True, True])
hparams.add_hparam('init_stride', 2)
hparams.add_hparam('init_kernel_size', 7)
hparams.add_hparam('init_maxpool', True)
hparams.add_hparam('strides', [1, 2, 2, 2])
hparams.add_hparam('num_channels_init_block', 64)
hparams.add_hparam('dim', '2d')
# Variable init
hparams.initializer = 'normal_unit_scaling'
hparams.initializer_gain = 2.
# Optimization
hparams.optimizer = 'Momentum'
hparams.optimizer_momentum_momentum = 0.9
hparams.optimizer_momentum_nesterov = True
hparams.weight_decay = 1e-4
hparams.clip_grad_norm = 0.0
# (base_lr=0.1) * (batch_size=128*8 (on TPU, or 8 GPUs)=1024) / (256.)
hparams.learning_rate = 0.4
hparams.learning_rate_decay_scheme = 'cosine'
# For image_imagenet224, 120k training steps, which effectively makes this a
# cosine decay (i.e. no cycles).
hparams.learning_rate_cosine_cycle_steps = 120000
# Can run with a batch size of 128 with Problem ImageImagenet224
hparams.batch_size = 128
return hparams | [
"Default hparams for Revnet."
] |
Please provide a description of the function:def revnet_cifar_base():
hparams = revnet_base()
hparams.num_channels_init_block = 32
hparams.first_batch_norm = [False, True, True]
hparams.init_stride = 1
hparams.init_kernel_size = 3
hparams.init_maxpool = False
hparams.strides = [1, 2, 2]
hparams.batch_size = 128
hparams.weight_decay = 1e-4
hparams.learning_rate = 0.1
hparams.learning_rate_cosine_cycle_steps = 5000
return hparams | [
"Tiny hparams suitable for CIFAR/etc."
] |
Please provide a description of the function:def revnet_110_cifar():
hparams = revnet_cifar_base()
hparams.bottleneck = False
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams | [
"Tiny hparams suitable for CIFAR/etc."
] |
Please provide a description of the function:def revnet_164_cifar():
hparams = revnet_cifar_base()
hparams.bottleneck = True
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams | [
"Tiny hparams suitable for CIFAR/etc."
] |
Please provide a description of the function:def revnet_range(rhp):
rhp.set_float('learning_rate', 0.05, 0.2, scale=rhp.LOG_SCALE)
rhp.set_float('weight_decay', 1e-5, 1e-3, scale=rhp.LOG_SCALE)
rhp.set_discrete('num_channels_init_block', [64, 128])
return rhp | [
"Hyperparameters for tuning revnet."
] |
Please provide a description of the function:def next_frame_basic_deterministic():
hparams = base.next_frame_base()
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 1
hparams.hidden_size = 64
hparams.batch_size = 4
hparams.num_hidden_layers = 2
hparams.optimizer = "Adafactor"
hparams.learning_rate_constant = 1.5
hparams.learning_rate_warmup_steps = 8000
hparams.learning_rate_schedule = "linear_warmup * constant * rsqrt_decay"
hparams.label_smoothing = 0.0
hparams.initializer = "uniform_unit_scaling"
hparams.initializer_gain = 1.3
hparams.weight_decay = 0.0
hparams.clip_grad_norm = 1.0
hparams.dropout = 0.1
hparams.add_hparam("residual_dropout", 0.5)
hparams.add_hparam("num_compress_steps", 6)
hparams.add_hparam("filter_double_steps", 2)
hparams.add_hparam("pixel_sampling_temperature", 0.0)
hparams.add_hparam("concat_internal_states", False)
hparams.add_hparam("do_autoregressive_rnn", False)
hparams.add_hparam("autoregressive_rnn_lookback", 8)
hparams.add_hparam("autoregressive_rnn_warmup_steps", 8000)
hparams.add_hparam("activation_fn", "relu")
hparams.bottom["inputs"] = modalities.video_identity_bottom
hparams.bottom["targets"] = modalities.video_identity_bottom
return hparams | [
"Basic 2-frame conv model."
] |
Please provide a description of the function:def next_frame_pixel_noise():
hparams = next_frame_basic_deterministic()
hparams.add_hparam("video_modality_input_noise", 0.05)
hparams.bottom["inputs"] = modalities.video_pixel_noise_bottom
hparams.top["inputs"] = modalities.video_top
return hparams | [
"Basic 2-frame conv model with pixel noise."
] |
Please provide a description of the function:def next_frame_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 | [
"Basic conv model with scheduled sampling."
] |
Please provide a description of the function:def next_frame_ae():
hparams = next_frame_basic_deterministic()
hparams.bottom["inputs"] = modalities.video_bitwise_bottom
hparams.top["inputs"] = modalities.video_top
hparams.hidden_size = 256
hparams.batch_size = 8
hparams.num_hidden_layers = 4
hparams.num_compress_steps = 4
hparams.dropout = 0.4
return hparams | [
"Conv autoencoder."
] |
Please provide a description of the function:def next_frame_ae_tiny():
hparams = next_frame_tiny()
hparams.bottom["inputs"] = modalities.video_bitwise_bottom
hparams.top["inputs"] = modalities.video_top
hparams.batch_size = 8
hparams.dropout = 0.4
return hparams | [
"Conv autoencoder, tiny set for testing."
] |
Please provide a description of the function:def next_frame_tiny():
hparams = next_frame_basic_deterministic()
hparams.hidden_size = 32
hparams.num_hidden_layers = 1
hparams.num_compress_steps = 2
hparams.filter_double_steps = 1
return hparams | [
"Tiny for testing."
] |
Please provide a description of the function:def next_frame_l1():
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 | [
"Basic conv model with L1 modality."
] |
Please provide a description of the function:def next_frame_l2():
hparams = next_frame_basic_deterministic()
hparams.loss["targets"] = modalities.video_l2_loss
hparams.top["targets"] = modalities.video_l1_top
hparams.video_modality_loss_cutoff = 2.4
return hparams | [
"Basic conv model with L2 modality."
] |
Please provide a description of the function:def next_frame_base_range(rhp):
rhp.set_float("dropout", 0.2, 0.6)
rhp.set_discrete("hidden_size", [64, 128, 256])
rhp.set_int("num_compress_steps", 5, 8)
rhp.set_discrete("batch_size", [4, 8, 16, 32])
rhp.set_int("num_hidden_layers", 1, 3)
rhp.set_int("filter_double_steps", 1, 6)
rhp.set_float("learning_rate_constant", 1., 4.)
rhp.set_int("learning_rate_warmup_steps", 500, 3000)
rhp.set_float("initializer_gain", 0.8, 1.8) | [
"Basic tuning grid."
] |
Please provide a description of the function:def next_frame_ae_range(rhp):
rhp.set_float("dropout", 0.3, 0.5)
rhp.set_int("num_compress_steps", 1, 3)
rhp.set_int("num_hidden_layers", 2, 6)
rhp.set_float("learning_rate_constant", 1., 2.)
rhp.set_float("initializer_gain", 0.8, 1.5)
rhp.set_int("filter_double_steps", 2, 3) | [
"Autoencoder world model tuning grid."
] |
Please provide a description of the function:def mqp_lm1b_base():
hparams = mtf_transformer2.mtf_unitransformer_base()
hparams.d_model = 1024
hparams.max_length = 256
hparams.batch_size = 256
# Parameters for my_layer_stack()
hparams.num_hidden_layers = 6
hparams.d_ff = 8192
hparams.d_kv = 128
hparams.num_heads = 8
hparams.learning_rate_decay_steps = 13600
hparams.layout = "batch:batch;vocab:model;d_ff:model;heads:model"
hparams.mesh_shape = "batch:32"
return hparams | [
"Series of architectures for language modeling."
] |
Please provide a description of the function:def initialize_env_specs(hparams, env_problem_name):
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) | [
"Initializes env_specs using the appropriate env."
] |
Please provide a description of the function:def train(hparams, output_dir, env_problem_name, report_fn=None):
env_fn = initialize_env_specs(hparams, env_problem_name)
tf.logging.vlog(1, "HParams in trainer_model_free.train : %s",
misc_utils.pprint_hparams(hparams))
tf.logging.vlog(1, "Using hparams.base_algo: %s", hparams.base_algo)
learner = rl_utils.LEARNERS[hparams.base_algo](
hparams.frame_stack_size, output_dir, output_dir, total_num_epochs=1
)
policy_hparams = trainer_lib.create_hparams(hparams.base_algo_params)
rl_utils.update_hparams_from_hparams(
policy_hparams, hparams, hparams.base_algo + "_"
)
tf.logging.vlog(1, "Policy HParams : %s",
misc_utils.pprint_hparams(policy_hparams))
# TODO(konradczechowski): remove base_algo dependance, when evaluation method
# will be decided
if hparams.base_algo == "ppo":
total_steps = policy_hparams.epochs_num
tf.logging.vlog(2, "total_steps: %d", total_steps)
eval_every_epochs = policy_hparams.eval_every_epochs
tf.logging.vlog(2, "eval_every_epochs: %d", eval_every_epochs)
if eval_every_epochs == 0:
eval_every_epochs = total_steps
policy_hparams.eval_every_epochs = 0
metric_name = rl_utils.get_metric_name(
sampling_temp=hparams.eval_sampling_temps[0],
max_num_noops=hparams.eval_max_num_noops,
clipped=False
)
tf.logging.vlog(1, "metric_name: %s", metric_name)
eval_metrics_dir = os.path.join(output_dir, "eval_metrics")
eval_metrics_dir = os.path.expanduser(eval_metrics_dir)
tf.gfile.MakeDirs(eval_metrics_dir)
eval_metrics_writer = tf.summary.FileWriter(eval_metrics_dir)
def evaluate_on_new_model(model_dir_path):
global step
eval_metrics = rl_utils.evaluate_all_configs(hparams, model_dir_path)
tf.logging.info(
"Agent eval metrics:\n{}".format(pprint.pformat(eval_metrics)))
rl_utils.summarize_metrics(eval_metrics_writer, eval_metrics, step)
if report_fn:
report_fn(eval_metrics[metric_name], step)
step += 1
policy_hparams.epochs_num = total_steps
policy_hparams.save_models_every_epochs = eval_every_epochs
else:
def evaluate_on_new_model(model_dir_path):
del model_dir_path
raise NotImplementedError(
"This function is currently implemented only for ppo")
learner.train(env_fn,
policy_hparams,
simulated=False,
save_continuously=True,
epoch=0,
model_save_fn=evaluate_on_new_model) | [
"Train."
] |
Please provide a description of the function:def learning_rate_factor(name, step_num, 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) | [
"Compute the designated learning rate factor from hparams."
] |
Please provide a description of the function:def learning_rate_schedule(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 | [
"Learning rate schedule based on hparams."
] |
Please provide a description of the function:def legacy_learning_rate_schedule(hparams):
step_num = _global_step(hparams)
warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps)
if hparams.learning_rate_decay_scheme == "noam":
ret = 5000.0 * hparams.hidden_size**-0.5 * tf.minimum(
(step_num + 1) * warmup_steps**-1.5, (step_num + 1)**-0.5)
else:
warmup_steps = hparams.learning_rate_warmup_steps
warmup = _learning_rate_warmup(warmup_steps, hparams=hparams)
decay = _learning_rate_decay(hparams, warmup_steps)
ret = tf.where(step_num < warmup_steps, warmup, decay)
optimizer_correction = 0.002 if "adam" in hparams.optimizer else 1.0
tf.logging.info("Base learning rate: %f", hparams.learning_rate)
return ret * optimizer_correction * hparams.learning_rate | [
"Backwards-compatible learning-rate schedule."
] |
Please provide a description of the function:def _global_step(hparams):
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) | [
"Adjust global step if a multi-step optimizer is used."
] |
Please provide a description of the function:def _piecewise_learning_rate(step, boundaries, values):
values = [1.0] + values
boundaries = [float(x) for x in boundaries]
return tf.train.piecewise_constant(
step, boundaries, values, name="piecewise_lr") | [
"Scale learning rate according to the given schedule.\n\n Multipliers are not cumulative.\n\n Args:\n step: global step\n boundaries: List of steps to transition on.\n values: Multiplier to apply at each boundary transition.\n\n Returns:\n Scaled value for the learning rate.\n "
] |
Please provide a description of the function:def _learning_rate_decay(hparams, warmup_steps=0):
scheme = hparams.learning_rate_decay_scheme
warmup_steps = tf.to_float(warmup_steps)
global_step = _global_step(hparams)
if not scheme or scheme == "none":
return tf.constant(1.)
tf.logging.info("Applying learning rate decay: %s.", scheme)
if scheme == "exp":
decay_steps = hparams.learning_rate_decay_steps
p = (global_step - warmup_steps) / decay_steps
if hparams.learning_rate_decay_staircase:
p = tf.floor(p)
return tf.pow(hparams.learning_rate_decay_rate, p)
if scheme == "piecewise":
return _piecewise_learning_rate(global_step,
hparams.learning_rate_boundaries,
hparams.learning_rate_multiples)
if scheme == "cosine":
cycle_steps = hparams.learning_rate_cosine_cycle_steps
cycle_position = global_step % (2 * cycle_steps)
cycle_position = cycle_steps - tf.abs(cycle_steps - cycle_position)
return 0.5 * (1 + tf.cos(np.pi * cycle_position / cycle_steps))
if scheme == "cyclelinear10x":
# Cycle the rate linearly by 10x every warmup_steps, up and down.
cycle_steps = warmup_steps
cycle_position = global_step % (2 * cycle_steps)
cycle_position = tf.to_float( # Normalize to the interval [-1, 1].
cycle_position - cycle_steps) / float(cycle_steps)
cycle_position = 1.0 - tf.abs(cycle_position) # 0 to 1 and back to 0.
return (cycle_position + 0.1) * 3.0 # 10x difference each cycle (0.3-3).
if scheme == "sqrt":
return _legacy_sqrt_decay(global_step - warmup_steps)
raise ValueError("Unrecognized learning rate decay scheme: %s" %
hparams.learning_rate_decay_scheme) | [
"Learning rate decay multiplier."
] |
Please provide a description of the function:def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None):
if not warmup_steps:
return tf.constant(1.)
tf.logging.info("Applying %s learning rate warmup for %d steps",
warmup_schedule, warmup_steps)
warmup_steps = tf.to_float(warmup_steps)
global_step = _global_step(hparams)
if warmup_schedule == "exp":
return tf.exp(tf.log(0.01) / warmup_steps)**(warmup_steps - global_step)
else:
assert warmup_schedule == "linear"
start = tf.constant(0.35)
return ((tf.constant(1.) - start) / warmup_steps) * global_step + start | [
"Learning rate warmup multiplier."
] |
Please provide a description of the function:def is_in_expr(expr, find):
return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find)) | [
"Returns True if `find` is a subtree of `expr`."
] |
Please provide a description of the function:def random_expr_with_required_var(depth, required_var, optional_list, ops):
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) | [
"Generate a random expression tree with a required variable.\n\n The required variable appears exactly once in the expression.\n\n Args:\n depth: At least one leaf will be this many levels down from the top.\n required_var: A char. This char is guaranteed to be placed exactly once at\n a leaf somewhere in the tree. This is the var to solve for.\n optional_list: A list of chars. These chars are randomly selected as leaf\n values. These are constant vars.\n ops: A list of ExprOp instances.\n\n Returns:\n An ExprNode instance which is the root of the generated expression tree.\n "
] |
Please provide a description of the function:def random_expr(depth, vlist, ops):
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) | [
"Generate a random expression tree.\n\n Args:\n depth: At least one leaf will be this many levels down from the top.\n vlist: A list of chars. These chars are randomly selected as leaf values.\n ops: A list of ExprOp instances.\n\n Returns:\n An ExprNode instance which is the root of the generated expression tree.\n "
] |
Please provide a description of the function:def algebra_inverse_solve(left, right, var, solve_ops):
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 | [
"Solves for the value of the given var in an expression.\n\n Args:\n left: The root of the ExprNode tree on the left side of the equals sign.\n right: The root of the ExprNode tree on the right side of the equals sign.\n var: A char. The variable to solve for.\n solve_ops: A dictionary with the following properties.\n * For each operator in the expression, there is a rule that determines\n how to cancel out a value either to the left or the right of that\n operator.\n * For each rule, there is an entry in the dictionary. The key is two\n chars- the op char, and either 'l' or 'r' meaning rule for canceling\n out the left or right sides. For example, '+l', '+r', '-l', '-r'.\n * The value of each entry is a function with the following signature:\n (left, right, to_tree) -> (new_from_tree, new_to_tree)\n left- Expression on left side of the op.\n right- Expression on the right side of the op.\n to_tree- The tree on the other side of the equal sign. The canceled\n out expression will be moved here.\n new_from_tree- The resulting from_tree after the algebraic\n manipulation.\n new_to_tree- The resulting to_tree after the algebraic manipulation.\n\n Returns:\n The root of an ExprNode tree which holds the value of `var` after solving.\n\n Raises:\n ValueError: If `var` does not appear exactly once in the equation (which\n includes the left and right sides).\n "
] |
Please provide a description of the function:def format_sympy_expr(sympy_expr, functions=None):
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 | [
"Convert sympy expression into a string which can be encoded.\n\n Args:\n sympy_expr: Any sympy expression tree or string.\n functions: Defines special functions. A dict mapping human readable string\n names, like \"log\", \"exp\", \"sin\", \"cos\", etc., to single chars. Each\n function gets a unique token, like \"L\" for \"log\".\n\n Returns:\n A string representation of the expression suitable for encoding as a\n sequence input.\n "
] |
Please provide a description of the function:def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth,
max_depth):
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 | [
"Randomly generate an algebra inverse dataset sample.\n\n Given an input equation and variable, produce the expression equal to the\n variable.\n\n Args:\n vlist: Variable list. List of chars that can be used in the expression.\n ops: List of ExprOp instances. The allowed operators for the expression.\n solve_ops: See `solve_ops` documentation in `algebra_inverse_solve`.\n min_depth: Expression trees will not have a smaller depth than this. 0 means\n there is just a variable. 1 means there is one operation.\n max_depth: Expression trees will not have a larger depth than this. To make\n all trees have the same depth, set this equal to `min_depth`.\n\n Returns:\n sample: String representation of the input. Will be of the form\n 'solve_var:left_side=right_side'.\n target: String representation of the solution.\n "
] |
Please provide a description of the function:def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth):
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 | [
"Randomly generate an algebra simplify dataset sample.\n\n Given an input expression, produce the simplified expression.\n\n Args:\n vlist: Variable list. List of chars that can be used in the expression.\n ops: List of ExprOp instances. The allowed operators for the expression.\n min_depth: Expression trees will not have a smaller depth than this. 0 means\n there is just a variable. 1 means there is one operation.\n max_depth: Expression trees will not have a larger depth than this. To make\n all trees have the same depth, set this equal to `min_depth`.\n\n Returns:\n sample: String representation of the input.\n target: String representation of the solution.\n "
] |
Please provide a description of the function:def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth,
functions):
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 | [
"Randomly generate a symbolic integral dataset sample.\n\n Given an input expression, produce the indefinite integral.\n\n Args:\n vlist: Variable list. List of chars that can be used in the expression.\n ops: List of ExprOp instances. The allowed operators for the expression.\n min_depth: Expression trees will not have a smaller depth than this. 0 means\n there is just a variable. 1 means there is one operation.\n max_depth: Expression trees will not have a larger depth than this. To make\n all trees have the same depth, set this equal to `min_depth`.\n functions: Defines special functions. A dict mapping human readable string\n names, like \"log\", \"exp\", \"sin\", \"cos\", etc., to single chars. Each\n function gets a unique token, like \"L\" for \"log\".\n\n Returns:\n sample: String representation of the input. Will be of the form\n 'var:expression'.\n target: String representation of the solution.\n "
] |
Please provide a description of the function:def math_dataset_init(alphabet_size=26, digits=None, functions=None):
ops_list = ["+", "-", "*", "/"]
ops = {
"+": ExprOp("+", 0, True),
"-": ExprOp("-", 0, False),
"*": ExprOp("*", 1, True),
"/": ExprOp("/", 1, False)
}
solve_ops = {
"+l": lambda l, r, to: (l, ExprNode(to, r, ops["-"])),
"+r": lambda l, r, to: (r, ExprNode(to, l, ops["-"])),
"-l": lambda l, r, to: (l, ExprNode(to, r, ops["+"])),
"-r": lambda l, r, to: (r, ExprNode(l, to, ops["-"])),
"*l": lambda l, r, to: (l, ExprNode(to, r, ops["/"])),
"*r": lambda l, r, to: (r, ExprNode(to, l, ops["/"])),
"/l": lambda l, r, to: (l, ExprNode(to, r, ops["*"])),
"/r": lambda l, r, to: (r, ExprNode(l, to, ops["/"])),
}
alphabet = (
[six.int2byte(ord("a") + c).decode("utf-8") for c in range(26)] +
[six.int2byte(ord("A") + c).decode("utf-8") for c in range(26)])
if alphabet_size > 52:
raise ValueError(
"alphabet_size cannot be greater than 52. Got %s." % alphabet_size)
if alphabet_size < 2:
raise ValueError(
"alphabet_size cannot be less than 2. Got %s." % alphabet_size)
if digits is not None and not 1 <= digits <= 10:
raise ValueError("digits cannot must be between 1 and 10. Got %s." % digits)
vlist = alphabet[:alphabet_size]
if digits is not None:
dlist = [str(d) for d in range(digits)]
else:
dlist = []
if functions is None:
functions = {}
flist = sorted(functions.values())
pad = "_"
tokens = [pad] + [":", "(", ")", "="] + ops_list + vlist + dlist + flist
if len(tokens) != len(set(tokens)):
raise ValueError("Duplicate token. Tokens: %s" % tokens)
token_map = dict([(t, i) for i, t in enumerate(tokens)])
def int_encoder(sequence):
return [token_map[s] for s in sequence]
def int_decoder(tensor_1d):
return "".join([tokens[i] for i in tensor_1d])
return AlgebraConfig(
vlist=vlist,
dlist=dlist,
flist=flist,
functions=functions,
ops=ops,
solve_ops=solve_ops,
int_encoder=int_encoder,
int_decoder=int_decoder) | [
"Initializes required objects to generate symbolic math datasets.\n\n Produces token set, ExprOp instances, solve_op dictionary, encoders, and\n decoders needed to generate the algebra inverse dataset.\n\n Args:\n alphabet_size: How many possible variables there are. Max 52.\n digits: How many numerical digits to encode as tokens, \"0\" through\n str(digits-1), or None to encode no digits.\n functions: Defines special functions. A dict mapping human readable string\n names, like \"log\", \"exp\", \"sin\", \"cos\", etc., to single chars. Each\n function gets a unique token, like \"L\" for \"log\".\n WARNING, Make sure these tokens do not conflict with the list of\n possible variable names.\n\n Returns:\n AlgebraConfig instance holding all the objects listed above.\n\n Raises:\n ValueError: If `alphabet_size` is not in range [2, 52].\n "
] |
Please provide a description of the function:def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2,
nbr_cases=10000):
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)
} | [
"Generate the algebra inverse dataset.\n\n Each sample is a symbolic math equation involving unknown variables. The\n task is to solve for the given variable. The target is the resulting\n expression.\n\n Args:\n alphabet_size: How many possible variables there are. Max 52.\n min_depth: Minimum depth of the expression trees on both sides of the\n equals sign in the equation.\n max_depth: Maximum depth of the expression trees on both sides of the\n equals sign in the equation.\n nbr_cases: The number of cases to generate.\n\n Yields:\n A dictionary {\"inputs\": input-list, \"targets\": target-list} where\n input-list are the tokens encoding the variable to solve for and the math\n equation, and target-list is a list of tokens encoding the resulting math\n expression after solving for the variable.\n\n Raises:\n ValueError: If `max_depth` < `min_depth`.\n "
] |
Please provide a description of the function:def algebra_simplify(alphabet_size=26,
min_depth=0,
max_depth=2,
nbr_cases=10000):
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)
} | [
"Generate the algebra simplify dataset.\n\n Each sample is a symbolic math expression involving unknown variables. The\n task is to simplify the expression. The target is the resulting expression.\n\n Args:\n alphabet_size: How many possible variables there are. Max 52.\n min_depth: Minimum depth of the expression trees on both sides of the\n equals sign in the equation.\n max_depth: Maximum depth of the expression trees on both sides of the\n equals sign in the equation.\n nbr_cases: The number of cases to generate.\n\n Yields:\n A dictionary {\"inputs\": input-list, \"targets\": target-list} where\n input-list are the tokens encoding the expression to simplify, and\n target-list is a list of tokens encoding the resulting math expression after\n simplifying.\n\n Raises:\n ValueError: If `max_depth` < `min_depth`.\n "
] |
Please provide a description of the function:def calculus_integrate(alphabet_size=26,
min_depth=0,
max_depth=2,
nbr_cases=10000):
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 | [
"Generate the calculus integrate dataset.\n\n Each sample is a symbolic math expression involving unknown variables. The\n task is to take the indefinite integral of the expression. The target is the\n resulting expression.\n\n Args:\n alphabet_size: How many possible variables there are. Max 26.\n min_depth: Minimum depth of the expression trees on both sides of the\n equals sign in the equation.\n max_depth: Maximum depth of the expression trees on both sides of the\n equals sign in the equation.\n nbr_cases: The number of cases to generate.\n\n Yields:\n A dictionary {\"inputs\": input-list, \"targets\": target-list} where\n input-list are the tokens encoding the variable to integrate with respect\n to and the expression to integrate, and target-list is a list of tokens\n encoding the resulting math expression after integrating.\n\n Raises:\n ValueError: If `max_depth` < `min_depth`, or if alphabet_size > 26.\n "
] |
Please provide a description of the function:def is_in(self, expr):
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 | [
"Returns True if `expr` is a subtree."
] |
Please provide a description of the function:def preprocess_example_common(example, mode, hparams):
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 | [
"Preprocessing steps common to all models."
] |
Please provide a description of the function:def _copy_problem_hparams(p_hparams):
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 | [
"Use input modality, vocab, and space id for target."
] |
Please provide a description of the function:def _reverse_problem_hparams(p_hparams):
p = p_hparams
# Swap modalities.
# TODO(trandustin): Note this assumes target modalities have feature name
# 'target', and each intended feature to swap has feature name 'input'.
# In the future, remove need for this behavior.
reversed_modality = {}
for feature_name in p.modality:
reversed_feature_name = feature_name.replace("target", "input")
if "target" in feature_name and reversed_feature_name in p.modality:
reversed_modality[feature_name] = p.modality[reversed_feature_name]
reversed_modality[reversed_feature_name] = p.modality[feature_name]
else:
reversed_modality[feature_name] = p.modality[feature_name]
p.modality = reversed_modality
# Swap vocab sizes.
reversed_vocab_size = {}
for feature_name in p.vocab_size:
reversed_feature_name = feature_name.replace("target", "input")
if "target" in feature_name and reversed_feature_name in p.vocab_size:
reversed_vocab_size[feature_name] = p.vocab_size[reversed_feature_name]
reversed_vocab_size[reversed_feature_name] = p.vocab_size[feature_name]
else:
reversed_vocab_size[feature_name] = p.vocab_size[feature_name]
p.vocab_size = reversed_vocab_size
# Swap vocabularies.
input_vocabulary = p.vocabulary.pop("inputs", None)
target_vocabulary = p.vocabulary.pop("targets", None)
if input_vocabulary is not None:
p.vocabulary["targets"] = input_vocabulary
if target_vocabulary is not None:
p.vocabulary["inputs"] = target_vocabulary
# Swap input/target space ids.
input_space_id = p.input_space_id
target_space_id = p.target_space_id
if input_space_id is not None:
p.target_space_id = input_space_id
else:
p.target_space_id = SpaceID.GENERIC
if target_space_id is not None:
p.input_space_id = target_space_id
else:
p.input_space_id = SpaceID.GENERIC
# Mark that p was reversed.
p.was_reversed = True | [
"Swap input/output modalities, vocab, and space ids."
] |
Please provide a description of the function:def _default_hparams():
return hparam.HParams(
# Use this parameter to get comparable perplexity numbers with different
# tokenizations. This value should be set to the ratio of the number of
# tokens in the test set according to the tokenization used to the number
# of tokens in the test set in the "official" tokenization. For
# example, if we are using a word-piece based model and we want to
# compute per-word perplexity, then we set loss_multiplier to the number
# of wordpieces per word in the test set.
loss_multiplier=1.0,
# Use this parameter to allow for larger sequences in the batch. Without
# the use of this parameter, the size of the inner two dimensions will
# be used to judge the sequence length.
batch_size_multiplier=1,
# During inference for autoregressive problems, if the batch_size is 1,
# the inference will stop when the model predict a text_encoder.EOS_ID
# token.
stop_at_eos=False,
# Modalities used to map from features to a space compatible with
# chosen model architecture. It comprises key-value pairs of a feature
# name (str) and its modality type.
modality={},
vocab_size={},
# Identifiers used to tell the model which input/target space will be
# expected. For example, it can tell that we expect French as characters
# as output, or Spanish as sound. Spaces defined as constants in SpaceID
# class.
input_space_id=SpaceID.GENERIC,
target_space_id=SpaceID.GENERIC) | [
"A set of basic model hyperparameters."
] |
Please provide a description of the function:def tpu_batch_size_per_shard(self, model_hparams):
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 | [
"Batch size in examples per TPU core.\n\n Args:\n model_hparams: model hyperparameters\n Returns:\n an integer\n "
] |
Please provide a description of the function:def preprocess(self, dataset, mode, hparams, interleave=True):
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 | [
"Runtime preprocessing on the whole dataset.\n\n Return a tf.data.Datset -- the preprocessed version of the given one.\n By default this function calls preprocess_example.\n\n Args:\n dataset: the Dataset of already decoded but not yet preprocessed features.\n mode: tf.estimator.ModeKeys\n hparams: HParams, model hyperparameters\n interleave: bool, whether to use parallel_interleave, which is faster\n but will alter the order of samples non-deterministically, or flat_map,\n which is slower but will preserve the sample order.\n\n Returns:\n a Dataset\n "
] |
Please provide a description of the function:def filepattern(self, data_dir, mode, shard=None):
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) | [
"Get filepattern for data files for mode.\n\n Matches mode to a suffix.\n * DatasetSplit.TRAIN: train\n * DatasetSplit.EVAL: dev\n * DatasetSplit.TEST: test\n * tf.estimator.ModeKeys.PREDICT: dev\n\n Args:\n data_dir: str, data directory.\n mode: DatasetSplit\n shard: int, if provided, will only read data from the specified shard.\n\n Returns:\n filepattern str\n "
] |
Please provide a description of the function:def get_hparams(self, model_hparams=None):
if self._hparams is not None:
return self._hparams
if model_hparams is None:
model_hparams = default_model_hparams()
if self._encoders is None:
data_dir = (model_hparams and hasattr(model_hparams, "data_dir") and
model_hparams.data_dir) or None
self.get_feature_encoders(data_dir)
hp = _default_hparams()
ret = self.hparams(hp, model_hparams)
if ret is not None:
raise ValueError("The Problem subclass hparams function should mutate "
"the defaults passed in and return None.")
hp.add_hparam("vocabulary", self._encoders)
hp.add_hparam("was_reversed", self._was_reversed)
hp.add_hparam("was_copy", self._was_copy)
if self._was_reversed:
_reverse_problem_hparams(hp)
if self._was_copy:
_copy_problem_hparams(hp)
self._hparams = hp
return self._hparams | [
"Returns problem_hparams."
] |
Please provide a description of the function:def maybe_reverse_features(self, feature_map):
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 | [
"Reverse features between inputs and targets if the problem is '_rev'."
] |
Please provide a description of the function: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):
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):
# 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 | [
"Build a Dataset for this problem.\n\n Args:\n mode: tf.estimator.ModeKeys; determines which files to read from.\n data_dir: directory that contains data files.\n num_threads: int, number of threads to use for decode and preprocess\n Dataset.map calls.\n output_buffer_size: int, how many elements to prefetch at end of pipeline.\n shuffle_files: whether to shuffle input files. Default behavior (i.e. when\n shuffle_files=None) is to shuffle if mode == TRAIN.\n hparams: HParams; hparams to be passed to\n Problem.preprocess_example and Problem.hparams. If None, will use a\n default set that is a no-op.\n preprocess: bool, whether to map the Dataset through\n Problem.preprocess_example.\n dataset_split: DatasetSplit, which split to read data\n from (TRAIN:\"-train\", EVAL:\"-dev\", \"test\":\"-test\"). Defaults to mode.\n shard: int, if provided, will only read data from the specified shard.\n partition_id: integer - which partition of the dataset to read from\n num_partitions: how many partitions in the dataset\n shuffle_buffer_size: if shuffle_files is True, this is the buffer size\n used to shuffle records.\n max_records: int, number of records to truncate to.\n\n Returns:\n Dataset containing dict<feature name, Tensor>.\n\n Raises:\n ValueError: if num_partitions is greater than the number of data files.\n ",
"Reads files from a string tensor or a dataset of filenames."
] |
Please provide a description of the function:def decode_example(self, serialized_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)) | [
"Return a dict of Tensors from a serialized tensorflow.Example."
] |
Please provide a description of the function:def feature_info(self):
if self._feature_info is not None:
return self._feature_info
assert self._hparams is not None
hp = self.get_hparams()
if self.has_inputs:
in_id = hp.input_space_id
out_id = hp.target_space_id
features = collections.defaultdict(FeatureInfo)
for feature_name, modality_cls in six.iteritems(hp.modality):
finfo = features[feature_name]
finfo.modality = modality_cls
finfo.vocab_size = hp.vocab_size[feature_name]
vocabs = hp.vocabulary
for name, encoder in six.iteritems(vocabs):
features[name].encoder = encoder
if self.has_inputs:
features["inputs"].space_id = in_id
features["targets"].space_id = out_id
self._feature_info = features
return features | [
"Retrieve dict<feature name, FeatureInfo>.\n\n Must first call Problem.get_hparams or Problem.dataset to have the problem's\n internal hparams already constructed.\n\n Returns:\n dict<feature name, FeatureInfo>\n "
] |
Please provide a description of the function:def make_estimator_input_fn(self,
mode,
hparams,
data_dir=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
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 | [
"Return input_fn wrapped for Estimator."
] |
Please provide a description of the function:def _dataset_partition(self, mode, config, params):
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 | [
"Which part of the training data to read.\n\n If there are multiple parallel calls to input_fn (multiple TPU hosts),\n then we want each one to read from a separate partition of the training\n data.\n\n Args:\n mode: tf.estimator.ModeKeys\n config: RunConfig\n params: A dict that contains parameters.\n Returns:\n partition_id: an integer\n num_partitions: an integer\n "
] |
Please provide a description of the function:def input_fn(self,
mode,
hparams,
data_dir=None,
params=None,
config=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
partition_id, num_partitions = self._dataset_partition(mode, config, params)
is_training = mode == tf.estimator.ModeKeys.TRAIN
if config and config.use_tpu:
num_threads = 64
else:
num_threads = data_reader.cpu_count() if is_training else 1
data_dir = data_dir or (hasattr(hparams, "data_dir") and hparams.data_dir)
dataset_kwargs = dataset_kwargs or {}
dataset_kwargs.update({
"mode": mode,
"data_dir": data_dir,
"num_threads": num_threads,
"hparams": hparams,
"partition_id": partition_id,
"num_partitions": num_partitions,
})
return data_reader.input_fn(
self.dataset(**dataset_kwargs),
self.filepattern(data_dir, mode),
self.skip_random_fraction_when_training,
self.batch_size_means_tokens,
self.get_hparams().batch_size_multiplier,
self.max_length(hparams),
mode,
hparams,
data_dir=data_dir,
params=params,
config=config,
force_repeat=force_repeat,
prevent_repeat=prevent_repeat) | [
"Builds input pipeline for problem.\n\n Args:\n mode: tf.estimator.ModeKeys\n hparams: HParams, model hparams\n data_dir: str, data directory; if None, will use hparams.data_dir\n params: dict, may include \"batch_size\"\n config: RunConfig; should have the data_parallelism attribute if not using\n TPU\n force_repeat: bool, whether to repeat the data even if not training\n prevent_repeat: bool, whether to not repeat when in training mode.\n Overrides force_repeat.\n dataset_kwargs: dict, if passed, will pass as kwargs to self.dataset\n method when called\n\n Returns:\n (features_dict<str name, Tensor feature>, Tensor targets)\n "
] |
Please provide a description of the function:def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False):
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) | [
"Input fn for serving export, starting from serialized example."
] |
Please provide a description of the function:def _get_hparams_path():
hparams_path = None
if FLAGS.output_dir:
hparams_path = os.path.join(FLAGS.output_dir, "hparams.json")
else:
tf.logging.warning(
"--output_dir not specified. Hyper-parameters will be infered from"
"--hparams_set and --hparams only. These may not match training time"
"hyper-parameters.")
return hparams_path | [
"Get hyper-parameters file path."
] |
Please provide a description of the function:def export_module_spec_with_checkpoint(module_spec,
checkpoint_path,
export_path,
scope_prefix=""):
# 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) | [
"Exports given checkpoint as tfhub module with given spec."
] |
Please provide a description of the function:def export_as_tfhub_module(model_name,
hparams,
decode_hparams,
problem,
checkpoint_path,
export_dir):
def hub_module_fn():
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="") | [
"Exports the last checkpoint from the directory as tfhub module.\n\n It creates the Module spec and signature (based on T2T problem information),\n which is later used to create and export the hub module.\n Module will be saved inside the ckpt_dir.\n\n Args:\n model_name: name of the model to be exported.\n hparams: T2T parameters, model graph will be based on them.\n decode_hparams: T2T parameters for decoding.\n problem: the name of the problem\n checkpoint_path: path to the checkpoint to be exported.\n export_dir: Directory to write the exported model to.\n ",
"Creates the TF graph for the hub module."
] |
Please provide a description of the function:def build_model(hparams_set, model_name, data_dir, problem_name, beam_size=1):
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 | [
"Build the graph required to fetch the attention weights.\n\n Args:\n hparams_set: HParams set to build the model with.\n model_name: Name of model.\n data_dir: Path to directory containing training data.\n problem_name: Name of problem.\n beam_size: (Optional) Number of beams to use when decoding a translation.\n If set to 1 (default) then greedy decoding is used.\n\n Returns:\n Tuple of (\n inputs: Input placeholder to feed in ids to be translated.\n targets: Targets placeholder to feed to translation when fetching\n attention weights.\n samples: Tensor representing the ids of the translation.\n att_mats: Tensors representing the attention weights.\n )\n "
] |
Please provide a description of the function:def get_att_mats(translate_model):
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 | [
"Get's the tensors representing the attentions from a build model.\n\n The attentions are stored in a dict on the Transformer object while building\n the graph.\n\n Args:\n translate_model: Transformer object to fetch the attention weights from.\n\n Returns:\n Tuple of attention matrices; (\n enc_atts: Encoder self attention weights.\n A list of `num_layers` numpy arrays of size\n (batch_size, num_heads, inp_len, inp_len)\n dec_atts: Decoder self attetnion weights.\n A list of `num_layers` numpy arrays of size\n (batch_size, num_heads, out_len, out_len)\n encdec_atts: Encoder-Decoder attention weights.\n A list of `num_layers` numpy arrays of size\n (batch_size, num_heads, out_len, inp_len)\n )\n "
] |
Please provide a description of the function:def encode(self, input_str):
inputs = self.encoders["inputs"].encode(input_str) + [EOS_ID]
batch_inputs = np.reshape(inputs, [1, -1, 1, 1]) # Make it 3D.
return batch_inputs | [
"Input str to features dict, ready for inference."
] |
Please provide a description of the function:def decode(self, integers):
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode(integers) | [
"List of ints to str."
] |
Please provide a description of the function:def decode_list(self, integers):
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode_list(integers) | [
"List of ints to list of str."
] |
Please provide a description of the function:def get_vis_data_from_string(self, sess, input_string):
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 | [
"Constructs the data needed for visualizing attentions.\n\n Args:\n sess: A tf.Session object.\n input_string: The input sentence to be translated and visualized.\n\n Returns:\n Tuple of (\n output_string: The translated sentence.\n input_list: Tokenized input sentence.\n output_list: Tokenized translation.\n att_mats: Tuple of attention matrices; (\n enc_atts: Encoder self attention weights.\n A list of `num_layers` numpy arrays of size\n (batch_size, num_heads, inp_len, inp_len)\n dec_atts: Decoder self attention weights.\n A list of `num_layers` numpy arrays of size\n (batch_size, num_heads, out_len, out_len)\n encdec_atts: Encoder-Decoder attention weights.\n A list of `num_layers` numpy arrays of size\n (batch_size, num_heads, out_len, inp_len)\n )\n "
] |
Please provide a description of the function:def glow_hparams():
hparams = common_hparams.basic_params1()
hparams.clip_grad_norm = None
hparams.weight_decay = 0.0
hparams.learning_rate_constant = 3e-4
hparams.batch_size = 32
# can be prev_level, prev_step or normal.
# see: glow_ops.merge_level_and_latent_dist
hparams.add_hparam("level_scale", "prev_level")
hparams.add_hparam("n_levels", 3)
hparams.add_hparam("n_bits_x", 8)
hparams.add_hparam("depth", 32)
# Activation - Relu or Gatu
hparams.add_hparam("activation", "relu")
# Coupling layer, additive or affine.
hparams.add_hparam("coupling", "affine")
hparams.add_hparam("coupling_width", 512)
hparams.add_hparam("coupling_dropout", 0.0)
hparams.add_hparam("top_prior", "single_conv")
# init_batch_size denotes the number of examples used for data-dependent
# initialization. A higher init_batch_size is required for training
# stability especially when hparams.batch_size is low.
hparams.add_hparam("init_batch_size", 256)
hparams.add_hparam("temperature", 1.0)
return hparams | [
"Glow Hparams."
] |
Please provide a description of the function:def shift_and_pad(tensor, shift, axis=0):
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 | [
"Shifts and pads with zero along an axis.\n\n Example:\n shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2]\n shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0]\n\n Args:\n tensor: Tensor; to be shifted and padded.\n shift: int; number of positions to shift by.\n axis: int; along which axis to shift and pad.\n\n Returns:\n A Tensor with the same shape as the input tensor.\n "
] |
Please provide a description of the function:def transformer_aux_base():
hparams = transformer.transformer_base()
hparams.shared_embedding_and_softmax_weights = False
hparams.add_hparam("shift_values", "1,2,3,4")
return hparams | [
"Set of hyperparameters."
] |
Please provide a description of the function:def transformer_aux_tiny():
hparams = transformer.transformer_tiny()
hparams.shared_embedding_and_softmax_weights = False
hparams.add_hparam("shift_values", "1,2")
return hparams | [
"Set of hyperparameters."
] |
Please provide a description of the function:def pixels_from_softmax(frame_logits, pure_sampling=False,
temperature=1.0, gumbel_noise_factor=0.2):
# 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) | [
"Given frame_logits from a per-pixel softmax, generate colors."
] |
Please provide a description of the function:def next_frame_base():
hparams = common_hparams.basic_params1()
# Loss cutoff.
hparams.add_hparam("video_modality_loss_cutoff", 0.01)
# Additional resizing the frames before feeding them to model.
hparams.add_hparam("preprocess_resize_frames", None)
# How many data points to suffle. Ideally should be part of problem not model!
hparams.add_hparam("shuffle_buffer_size", 128)
# Tiny mode. For faster tests.
hparams.add_hparam("tiny_mode", False)
# In case a model supports smaller/faster version.
hparams.add_hparam("small_mode", False)
# In case a model has stochastic version.
hparams.add_hparam("stochastic_model", False)
# Internal loss for recurrent models.
hparams.add_hparam("internal_loss", True)
# choose from: concat, multiplicative, multi_additive
hparams.add_hparam("action_injection", "multi_additive")
# Scheduled sampling method. Choose between
# ground_truth_only, prediction_only, prob, count, prob_inverse_exp.
hparams.add_hparam("scheduled_sampling_mode", "prediction_only")
hparams.add_hparam("scheduled_sampling_decay_steps", 10000)
hparams.add_hparam("scheduled_sampling_max_prob", 1.0)
hparams.add_hparam("scheduled_sampling_k", 900.0)
return hparams | [
"Common HParams for next_frame models."
] |
Please provide a description of the function:def remove_time_limit_wrapper(env):
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 | [
"Removes top level TimeLimit Wrapper.\n\n Removes TimeLimit Wrapper from top level if exists, throws error if any other\n TimeLimit Wrapper is present in stack.\n\n Args:\n env: environment\n\n Returns:\n the env with removed time limit wrapper.\n "
] |
Please provide a description of the function:def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env,
rendered_env_resize_to, sticky_actions):
# 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 | [
"Wraps a gym environment. see make_gym_env for details."
] |
Please provide a description of the function: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):
env = gym.make(name)
return gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env,
rendered_env, rendered_env_resize_to, sticky_actions) | [
"Create a gym env optionally with a time limit and maxskip wrapper.\n\n NOTE: The returned env may already be wrapped with TimeLimit!\n\n Args:\n name: `str` - base name of the gym env to make.\n rl_env_max_episode_steps: `int` or None - Using any value < 0 returns the\n env as-in, otherwise we impose the requested timelimit. Setting this to\n None returns a wrapped env that doesn't have a step limit.\n maxskip_env: whether to also use MaxAndSkip wrapper before time limit.\n rendered_env: whether to force render for observations. Use this for\n environments that are not natively rendering the scene for observations.\n rendered_env_resize_to: a list of [height, width] to change the original\n resolution of the native environment render.\n sticky_actions: whether to use sticky_actions before MaxAndSkip wrapper.\n\n Returns:\n An instance of `gym.Env` or `gym.Wrapper`.\n "
] |
Please provide a description of the function:def register_gym_env(class_entry_point, version="v0", kwargs=None):
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) | [
"Registers the class in Gym and returns the registered name and the env."
] |
Please provide a description of the function:def step(self, action):
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 | [
"Repeat action, sum reward, and max over last observations."
] |
Please provide a description of the function:def _handle_errors(errors):
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)) | [
"Log out and possibly reraise errors during import."
] |
Please provide a description of the function:def create_hparams(hparams_set,
hparams_overrides_str="",
data_dir=None,
problem_name=None,
hparams_path=None):
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 | [
"Create HParams with data_dir and problem hparams, if kwargs provided."
] |
Please provide a description of the function:def create_hparams_from_json(json_path, hparams=None):
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 | [
"Loading hparams from json; can also start from hparams if specified."
] |
Please provide a description of the function:def add_problem_hparams(hparams, problem_name_or_instance):
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 | [
"Add problem hparams for the problems."
] |
Please provide a description of the function:def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01):
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 | [
"Loads exampls from the tsv file.\n\n Args:\n tmp_dir: temp directory.\n prop_train: proportion of the train data\n prop_val: proportion of the validation data\n\n Returns:\n All examples in the dataset pluse train, test, and development splits.\n\n "
] |
Please provide a description of the function:def _get_cifar(directory, url):
filename = os.path.basename(url)
path = generator_utils.maybe_download(directory, filename, url)
tarfile.open(path, "r:gz").extractall(directory) | [
"Download and extract CIFAR to directory unless it is there."
] |
Please provide a description of the function:def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0):
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]) | [
"Image generator for CIFAR-10 and 100.\n\n Args:\n cifar_version: string; one of \"cifar10\" or \"cifar100\"\n tmp_dir: path to temporary storage directory.\n training: a Boolean; if true, we use the train set, otherwise the test set.\n how_many: how many images and labels to generate.\n start_from: from which image to start.\n\n Returns:\n An instance of image_generator that produces CIFAR-10 images and labels.\n "
] |
Please provide a description of the function:def rlmb_ppo_base():
hparams = _rlmb_base()
ppo_params = dict(
base_algo="ppo",
base_algo_params="ppo_original_params",
# Number of real environments to train on simultaneously.
real_batch_size=1,
# Number of simulated environments to train on simultaneously.
simulated_batch_size=16,
eval_batch_size=32,
# Unused; number of PPO epochs is calculated from the real frame limit.
real_ppo_epochs_num=0,
# Number of frames that can be taken from the simulated environment before
# it diverges, used for training the agent.
ppo_epochs_num=1000, # This should be enough to see something
# Should be equal to simulated_rollout_length.
# TODO(koz4k): Uncouple this by outputing done from SimulatedBatchEnv.
ppo_epoch_length=hparams.simulated_rollout_length,
# Do not eval since simulated batch env does not produce dones
ppo_eval_every_epochs=0,
ppo_learning_rate_constant=1e-4, # Will be changed, just so it exists.
# This needs to be divisible by real_ppo_effective_num_agents.
real_ppo_epoch_length=16 * 200,
real_ppo_learning_rate_constant=1e-4,
real_ppo_effective_num_agents=16,
real_ppo_eval_every_epochs=0,
simulation_flip_first_random_for_beginning=True,
)
update_hparams(hparams, ppo_params)
return hparams | [
"HParams for PPO base."
] |
Please provide a description of the function:def rlmb_dqn_base():
hparams = _rlmb_base()
simulated_rollout_length = 10
dqn_params = dict(
base_algo="dqn",
base_algo_params="dqn_original_params",
real_batch_size=1,
simulated_batch_size=16,
dqn_agent_generates_trainable_dones=False,
eval_batch_size=1,
# Must be equal to dqn_time_limit for now
simulated_rollout_length=simulated_rollout_length,
dqn_time_limit=simulated_rollout_length,
simulation_flip_first_random_for_beginning=False,
dqn_eval_episodes_num=3,
# TODO(kc): only for model-free compatibility, remove this
epochs_num=-1,
)
update_hparams(hparams, dqn_params)
return hparams | [
"rlmb_dqn_base params."
] |
Please provide a description of the function:def rlmb_ppo_quick():
hparams = rlmb_ppo_base()
hparams.epochs = 2
hparams.model_train_steps = 25000
hparams.ppo_epochs_num = 700
hparams.ppo_epoch_length = 50
return hparams | [
"Base setting but quicker with only 2 epochs."
] |
Please provide a description of the function:def rlmb_base_stochastic():
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 | [
"Base setting with a stochastic next-frame model."
] |
Please provide a description of the function:def rlmb_base_stochastic_discrete():
hparams = rlmb_base()
hparams.learning_rate_bump = 1.0
hparams.grayscale = False
hparams.generative_model = "next_frame_basic_stochastic_discrete"
hparams.generative_model_params = "next_frame_basic_stochastic_discrete"
# The parameters below are the same as base, but repeated for easier reading.
hparams.ppo_epoch_length = 50
hparams.simulated_rollout_length = 50
hparams.simulated_batch_size = 16
return hparams | [
"Base setting with stochastic discrete model."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.