Code stringlengths 103 85.9k | Summary listlengths 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
... | [
"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 ... | [
"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,
... | [
"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 wit... |
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.... | [
"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.d... | [
"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.l... | [
"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 ... |
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/... | [
"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... | [
"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 firs... |
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... |
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... | [
"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... |
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=... | [
"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... |
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
resid... | [
"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... |
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.rel... | [
"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 ... |
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,
... | [
"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 m... |
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, Tr... | [
"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... | [
"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"
hpar... | [
"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... | [
"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... | [
"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_doub... | [
"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
hpar... | [
"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_... | [
"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... | [
"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 / hparam... | [
"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)
schedul... | [
"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 ... | [
"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."
... | [
"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 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_flo... | [
"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 = rand... | [
"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 somewhe... |
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_s... | [
"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 exp... |
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. "
... | [
"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 followi... |
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... |
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 si... | [
"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 ... |
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 t... |
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... | [
"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 tre... |
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 = {
... | [
"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 di... |
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_de... | [
"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 t... |
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. "
... | [
"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 ex... |
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. "
... | [
"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_de... |
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... | [
"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"] ... | [
"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 beh... | [
"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... | [
"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)
... | [
"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 h... |
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.e... | [
"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 provid... |
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... | [
"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... | [
"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,
... | [
"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 ma... |
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.... | [
"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 = coll... | [
"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,
... | [
"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 = ... | [
"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... |
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):
partiti... | [
"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 ... |
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(... | [
"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 -... | [
"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 kno... | [
"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():
m... | [
"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 ... |
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.EVA... | [
"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... |
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":
po... | [
"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:... |
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 th... | [
"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 ... |
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_late... | [
"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:
... | [
"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 an... |
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(f... | [
"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... | [
"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... | [
"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_step... | [
"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_wrap... | [
"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 ... |
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-{}-{}".for... | [
"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]... | [
"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_st... | [
"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(hpar... | [
"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.
... | [
"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)
... | [
"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 % 10... | [
"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_... | [
"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:... |
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 tra... | [
"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,... | [
"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"
# T... | [
"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.