INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Downsamples x by stride using average pooling. | def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'):
"""Downsamples 'x' by `stride` using average pooling.
Args:
x: input tensor of size [N, H, W, C]
output_channels: Desired number of output channels.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: What stride to ... |
Standard ResNet initial block used as first RevNet block. | def init(images, num_channels, dim='2d', stride=2,
kernel_size=7, maxpool=True, training=True, scope='init'):
"""Standard ResNet initial block used as first RevNet block.
Args:
images: [N, H, W, 3] tensor of input images to the model.
num_channels: Output depth of convolutional layer in initial bl... |
Implements bottleneck RevNet unit from authors RevNet architecture. | def unit(x1, x2, block_num, depth, num_layers, dim='2d',
bottleneck=True, first_batch_norm=True, stride=1, training=True):
"""Implements bottleneck RevNet unit from authors' RevNet architecture.
Args:
x1: [N, H, W, C] tensor of network activations.
x2: [N, H, W, C] tensor of network activations.
... |
Converts activations from last RevNet block to pre - logits. | def final_block(x1, x2, dim='2d', training=True, scope='final_block'):
"""Converts activations from last RevNet block to pre-logits.
Args:
x1: [NxHxWxC] tensor of network activations.
x2: [NxHxWxC] tensor of network activations.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
training: True for ... |
Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. | def revnet(inputs, hparams, reuse=None):
"""Uses Tensor2Tensor memory optimized RevNet block to build a RevNet.
Args:
inputs: [NxHxWx3] tensor of input images to the model.
hparams: HParams object that contains the following parameters,
in addition to the parameters contained in the basic_params1() o... |
Default hparams for Revnet. | def revnet_base():
"""Default hparams for Revnet."""
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, Tr... |
Tiny hparams suitable for CIFAR/ etc. | def revnet_cifar_base():
"""Tiny hparams suitable for CIFAR/etc."""
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_si... |
Tiny hparams suitable for CIFAR/ etc. | def revnet_110_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
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. | def revnet_164_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = True
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams |
Hyperparameters for tuning revnet. | def revnet_range(rhp):
"""Hyperparameters for tuning revnet."""
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 |
Basic 2 - frame conv model. | def next_frame_basic_deterministic():
"""Basic 2-frame conv model."""
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_r... |
Basic 2 - frame conv model with pixel noise. | def next_frame_pixel_noise():
"""Basic 2-frame conv model with 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 conv model with scheduled sampling. | def next_frame_sampling():
"""Basic conv model with scheduled sampling."""
hparams = next_frame_basic_deterministic()
hparams.scheduled_sampling_mode = "prob_inverse_exp"
hparams.scheduled_sampling_max_prob = 1.0
hparams.scheduled_sampling_decay_steps = 10000
return hparams |
Conv autoencoder. | def next_frame_ae():
"""Conv autoencoder."""
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
... |
Conv autoencoder tiny set for testing. | def next_frame_ae_tiny():
"""Conv autoencoder, tiny set for testing."""
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 |
Tiny for testing. | def next_frame_tiny():
"""Tiny for testing."""
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 |
Basic conv model with L1 modality. | def next_frame_l1():
"""Basic conv model with L1 modality."""
hparams = next_frame_basic_deterministic()
hparams.loss["targets"] = modalities.video_l1_loss
hparams.top["targets"] = modalities.video_l1_top
hparams.video_modality_loss_cutoff = 2.4
return hparams |
Basic conv model with L2 modality. | def next_frame_l2():
"""Basic conv model with L2 modality."""
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 tuning grid. | def next_frame_base_range(rhp):
"""Basic tuning grid."""
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)... |
Autoencoder world model tuning grid. | def next_frame_ae_range(rhp):
"""Autoencoder world model tuning grid."""
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_... |
Series of architectures for language modeling. | def mqp_lm1b_base():
"""Series of architectures for language modeling."""
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... |
Initializes env_specs using the appropriate env. | def initialize_env_specs(hparams, env_problem_name):
"""Initializes env_specs using the appropriate env."""
if env_problem_name:
env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size)
else:
env = rl_utils.setup_env(hparams, hparams.batch_size,
hparams.eval... |
Train. | def train(hparams, output_dir, env_problem_name, report_fn=None):
"""Train."""
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.... |
Compute the designated learning rate factor from hparams. | def learning_rate_factor(name, step_num, hparams):
"""Compute the designated learning rate factor from hparams."""
if name == "constant":
tf.logging.info("Base learning rate: %f", hparams.learning_rate_constant)
return hparams.learning_rate_constant
elif name == "linear_warmup":
return tf.minimum(1.0,... |
Learning rate schedule based on hparams. | def learning_rate_schedule(hparams):
"""Learning rate schedule based on hparams."""
mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True)
mlperf_log.transformer_print(
key=mlperf_log.OPT_LR_WARMUP_STEPS,
value=hparams.learning_rate_warmup_steps)
step_num = _global_step(hparams)
schedu... |
Backwards - compatible learning - rate schedule. | def legacy_learning_rate_schedule(hparams):
"""Backwards-compatible learning-rate schedule."""
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... |
Adjust global step if a multi - step optimizer is used. | def _global_step(hparams):
"""Adjust global step if a multi-step optimizer is used."""
step = tf.to_float(tf.train.get_or_create_global_step())
multiplier = hparams.optimizer_multistep_accumulate_steps
if not multiplier:
return step
tf.logging.info("Dividing global step by %d for multi-step optimizer."
... |
Scale learning rate according to the given schedule. | def _piecewise_learning_rate(step, boundaries, values):
"""Scale learning rate according to the given schedule.
Multipliers are not cumulative.
Args:
step: global step
boundaries: List of steps to transition on.
values: Multiplier to apply at each boundary transition.
Returns:
Scaled value fo... |
Learning rate decay multiplier. | def _learning_rate_decay(hparams, warmup_steps=0):
"""Learning rate decay multiplier."""
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... |
Learning rate warmup multiplier. | def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None):
"""Learning rate warmup multiplier."""
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(warm... |
Returns True if find is a subtree of expr. | def is_in_expr(expr, find):
"""Returns True if `find` is a subtree of `expr`."""
return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find)) |
Generate a random expression tree with a required variable. | def random_expr_with_required_var(depth, required_var, optional_list, ops):
"""Generate a random expression tree with a required variable.
The required variable appears exactly once in the expression.
Args:
depth: At least one leaf will be this many levels down from the top.
required_var: A char. This c... |
Generate a random expression tree. | def random_expr(depth, vlist, ops):
"""Generate a random expression tree.
Args:
depth: At least one leaf will be this many levels down from the top.
vlist: A list of chars. These chars are randomly selected as leaf values.
ops: A list of ExprOp instances.
Returns:
An ExprNode instance which is t... |
Solves for the value of the given var in an expression. | def algebra_inverse_solve(left, right, var, solve_ops):
"""Solves for the value of the given var in an expression.
Args:
left: The root of the ExprNode tree on the left side of the equals sign.
right: The root of the ExprNode tree on the right side of the equals sign.
var: A char. The variable to solve... |
Convert sympy expression into a string which can be encoded. | def format_sympy_expr(sympy_expr, functions=None):
"""Convert sympy expression into a string which can be encoded.
Args:
sympy_expr: Any sympy expression tree or string.
functions: Defines special functions. A dict mapping human readable string
names, like "log", "exp", "sin", "cos", etc., to singl... |
Randomly generate an algebra inverse dataset sample. | def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth,
max_depth):
"""Randomly generate an algebra inverse dataset sample.
Given an input equation and variable, produce the expression equal to the
variable.
Args:
vlist: Variable list. List of chars that c... |
Randomly generate an algebra simplify dataset sample. | def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth):
"""Randomly generate an algebra simplify dataset sample.
Given an input expression, produce the simplified expression.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The ... |
Randomly generate a symbolic integral dataset sample. | def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth,
functions):
"""Randomly generate a symbolic integral dataset sample.
Given an input expression, produce the indefinite integral.
Args:
vlist: Variable list. List of chars that can be used in the e... |
Initializes required objects to generate symbolic math datasets. | def math_dataset_init(alphabet_size=26, digits=None, functions=None):
"""Initializes required objects to generate symbolic math datasets.
Produces token set, ExprOp instances, solve_op dictionary, encoders, and
decoders needed to generate the algebra inverse dataset.
Args:
alphabet_size: How many possible... |
Generate the algebra inverse dataset. | def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2,
nbr_cases=10000):
"""Generate the algebra inverse dataset.
Each sample is a symbolic math equation involving unknown variables. The
task is to solve for the given variable. The target is the resulting
expression.
Args:
a... |
Generate the algebra simplify dataset. | def algebra_simplify(alphabet_size=26,
min_depth=0,
max_depth=2,
nbr_cases=10000):
"""Generate the algebra simplify dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to simplify the expression. The target is ... |
Generate the calculus integrate dataset. | def calculus_integrate(alphabet_size=26,
min_depth=0,
max_depth=2,
nbr_cases=10000):
"""Generate the calculus integrate dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to take the indefinite integral ... |
Returns True if expr is a subtree. | def is_in(self, expr):
"""Returns True if `expr` is a subtree."""
if expr == self:
return True
is_in_left = is_in_expr(self.left, expr)
is_in_right = is_in_expr(self.right, expr)
return is_in_left or is_in_right |
Preprocessing steps common to all models. | def preprocess_example_common(example, mode, hparams):
"""Preprocessing steps common to all models."""
if "inputs" in example and hparams.max_input_seq_length > 0:
example["inputs"] = example["inputs"][:hparams.max_input_seq_length]
if hparams.prepend_mode != "none":
if mode == tf.estimator.ModeKeys.PREDI... |
Use input modality vocab and space id for target. | def _copy_problem_hparams(p_hparams):
"""Use input modality, vocab, and space id for target."""
p = p_hparams
# Duplicate input modality.
p.modality["targets"] = p.modality["inputs"]
# Duplicate input vocab size.
p.vocab_size["targets"] = p.vocab_size["inputs"]
# Duplicate input vocabulary.
p.vocabulary... |
Swap input/ output modalities vocab and space ids. | def _reverse_problem_hparams(p_hparams):
"""Swap input/output modalities, vocab, and space ids."""
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 ... |
A set of basic model hyperparameters. | def _default_hparams():
"""A set of basic model hyperparameters."""
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 t... |
Batch size in examples per TPU core. | def tpu_batch_size_per_shard(self, model_hparams):
"""Batch size in examples per TPU core.
Args:
model_hparams: model hyperparameters
Returns:
an integer
"""
if self.batch_size_means_tokens and not model_hparams.use_fixed_batch_size:
return model_hparams.batch_size // self.max_len... |
Runtime preprocessing on the whole dataset. | def preprocess(self, dataset, mode, hparams, interleave=True):
"""Runtime preprocessing on the whole dataset.
Return a tf.data.Datset -- the preprocessed version of the given one.
By default this function calls preprocess_example.
Args:
dataset: the Dataset of already decoded but not yet preproc... |
Get filepattern for data files for mode. | def filepattern(self, data_dir, mode, shard=None):
"""Get filepattern for data files for mode.
Matches mode to a suffix.
* DatasetSplit.TRAIN: train
* DatasetSplit.EVAL: dev
* DatasetSplit.TEST: test
* tf.estimator.ModeKeys.PREDICT: dev
Args:
data_dir: str, data directory.
mode... |
Returns problem_hparams. | def get_hparams(self, model_hparams=None):
"""Returns problem_hparams."""
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") a... |
Reverse features between inputs and targets if the problem is _rev. | def maybe_reverse_features(self, feature_map):
"""Reverse features between inputs and targets if the problem is '_rev'."""
if not self._was_reversed:
return
inputs = feature_map.pop("inputs", None)
targets = feature_map.pop("targets", None)
inputs_seg = feature_map.pop("inputs_segmentation", N... |
Build a Dataset for this problem. | 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,... |
Return a dict of Tensors from a serialized tensorflow. Example. | def decode_example(self, serialized_example):
"""Return a dict of Tensors from a serialized tensorflow.Example."""
data_fields, data_items_to_decoders = self.example_reading_spec()
# Necessary to rejoin examples in the correct order with the Cloud ML Engine
# batch prediction API.
data_fields["batch... |
Retrieve dict<feature name FeatureInfo >. | def feature_info(self):
"""Retrieve dict<feature name, FeatureInfo>.
Must first call Problem.get_hparams or Problem.dataset to have the problem's
internal hparams already constructed.
Returns:
dict<feature name, FeatureInfo>
"""
if self._feature_info is not None:
return self._featu... |
Return input_fn wrapped for Estimator. | def make_estimator_input_fn(self,
mode,
hparams,
data_dir=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
"""Retur... |
Which part of the training data to read. | def _dataset_partition(self, mode, config, params):
"""Which part of the training data to read.
If there are multiple parallel calls to input_fn (multiple TPU hosts),
then we want each one to read from a separate partition of the training
data.
Args:
mode: tf.estimator.ModeKeys
config:... |
Builds input pipeline for problem. | def input_fn(self,
mode,
hparams,
data_dir=None,
params=None,
config=None,
force_repeat=False,
prevent_repeat=False,
dataset_kwargs=None):
"""Builds input pipeline for problem.
Args:
mo... |
Input fn for serving export starting from serialized example. | def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False):
"""Input fn for serving export, starting from serialized example."""
mode = tf.estimator.ModeKeys.PREDICT
serialized_example = tf.placeholder(
dtype=tf.string, shape=[None], name="serialized_example")
dataset = tf.data.Data... |
Get hyper - parameters file path. | def _get_hparams_path():
"""Get hyper-parameters file 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... |
Exports given checkpoint as tfhub module with given spec. | def export_module_spec_with_checkpoint(module_spec,
checkpoint_path,
export_path,
scope_prefix=""):
"""Exports given checkpoint as tfhub module with given spec."""
# The main requirement is that it ... |
Exports the last checkpoint from the directory as tfhub module. | def export_as_tfhub_module(model_name,
hparams,
decode_hparams,
problem,
checkpoint_path,
export_dir):
"""Exports the last checkpoint from the directory as tfhub module.
It creates... |
Build the graph required to fetch the attention weights. | def build_model(hparams_set, model_name, data_dir, problem_name, beam_size=1):
"""Build the graph required to fetch the attention weights.
Args:
hparams_set: HParams set to build the model with.
model_name: Name of model.
data_dir: Path to directory containing training data.
problem_name: Name of p... |
Get s the tensors representing the attentions from a build model. | def get_att_mats(translate_model):
"""Get's the tensors representing the attentions from a build model.
The attentions are stored in a dict on the Transformer object while building
the graph.
Args:
translate_model: Transformer object to fetch the attention weights from.
Returns:
Tuple of attention ma... |
Input str to features dict ready for inference. | def encode(self, input_str):
"""Input str to features dict, ready for inference."""
inputs = self.encoders["inputs"].encode(input_str) + [EOS_ID]
batch_inputs = np.reshape(inputs, [1, -1, 1, 1]) # Make it 3D.
return batch_inputs |
List of ints to str. | def decode(self, integers):
"""List of ints to str."""
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode(integers) |
List of ints to list of str. | def decode_list(self, integers):
"""List of ints to list of str."""
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode_list(integers) |
Constructs the data needed for visualizing attentions. | def get_vis_data_from_string(self, sess, input_string):
"""Constructs the data needed for visualizing attentions.
Args:
sess: A tf.Session object.
input_string: The input sentence to be translated and visualized.
Returns:
Tuple of (
output_string: The translated sentence.
... |
Glow Hparams. | def glow_hparams():
"""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_hpar... |
Shifts and pads with zero along an axis. | def shift_and_pad(tensor, shift, axis=0):
"""Shifts and pads with zero along an axis.
Example:
shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2]
shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0]
Args:
tensor: Tensor; to be shifted and padded.
shift: int; number of positions to shift by.
axis: ... |
Set of hyperparameters. | def transformer_aux_base():
"""Set of hyperparameters."""
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. | def transformer_aux_tiny():
"""Set of hyperparameters."""
hparams = transformer.transformer_tiny()
hparams.shared_embedding_and_softmax_weights = False
hparams.add_hparam("shift_values", "1,2")
return hparams |
Given frame_logits from a per - pixel softmax generate colors. | def pixels_from_softmax(frame_logits, pure_sampling=False,
temperature=1.0, gumbel_noise_factor=0.2):
"""Given frame_logits from a per-pixel softmax, generate colors."""
# If we're purely sampling, just sample each pixel.
if pure_sampling or temperature == 0.0:
return common_layers.sam... |
Common HParams for next_frame models. | def next_frame_base():
"""Common HParams for next_frame models."""
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 d... |
Removes top level TimeLimit Wrapper. | def remove_time_limit_wrapper(env):
"""Removes top level TimeLimit Wrapper.
Removes TimeLimit Wrapper from top level if exists, throws error if any other
TimeLimit Wrapper is present in stack.
Args:
env: environment
Returns:
the env with removed time limit wrapper.
"""
if isinstance(env, gym.wr... |
Wraps a gym environment. see make_gym_env for details. | def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env,
rendered_env_resize_to, sticky_actions):
"""Wraps a gym environment. see make_gym_env for details."""
# rl_env_max_episode_steps is None or int.
assert ((not rl_env_max_episode_steps) or
isinstance(rl_env_m... |
Create a gym env optionally with a time limit and maxskip wrapper. | def make_gym_env(name,
rl_env_max_episode_steps=-1,
maxskip_env=False,
rendered_env=False,
rendered_env_resize_to=None,
sticky_actions=False):
"""Create a gym env optionally with a time limit and maxskip wrapper.
NOTE: The returne... |
Registers the class in Gym and returns the registered name and the env. | def register_gym_env(class_entry_point, version="v0", kwargs=None):
"""Registers the class in Gym and returns the registered name and the env."""
split_on_colon = class_entry_point.split(":")
assert len(split_on_colon) == 2
class_name = split_on_colon[1]
# We have to add the version to conform to gym's API.... |
Repeat action sum reward and max over last observations. | def step(self, action):
"""Repeat action, sum reward, and max over last observations."""
total_reward = 0.0
done = None
for i in range(self._skip):
obs, reward, done, info = self.env.step(action)
if i == self._skip - 2:
self._obs_buffer[0] = obs
if i == self._skip - 1:
... |
Log out and possibly reraise errors during import. | def _handle_errors(errors):
"""Log out and possibly reraise errors during import."""
if not errors:
return
log_all = True # pylint: disable=unused-variable
err_msg = "T2T: skipped importing {num_missing} data_generators modules."
print(err_msg.format(num_missing=len(errors)))
for module, err in errors:... |
Create HParams with data_dir and problem hparams if kwargs provided. | def create_hparams(hparams_set,
hparams_overrides_str="",
data_dir=None,
problem_name=None,
hparams_path=None):
"""Create HParams with data_dir and problem hparams, if kwargs provided."""
hparams = registry.hparams(hparams_set)
if hparams... |
Loading hparams from json ; can also start from hparams if specified. | def create_hparams_from_json(json_path, hparams=None):
"""Loading hparams from json; can also start from hparams if specified."""
tf.logging.info("Loading hparams from existing json %s" % json_path)
with tf.gfile.Open(json_path, "r") as f:
hparams_values = json.load(f)
# Prevent certain keys from overwrit... |
Add problem hparams for the problems. | def add_problem_hparams(hparams, problem_name_or_instance):
"""Add problem hparams for the problems."""
if isinstance(problem_name_or_instance, problem_lib.Problem):
problem = problem_name_or_instance
else:
problem = registry.problem(problem_name_or_instance)
p_hparams = problem.get_hparams(hparams)
h... |
Loads exampls from the tsv file. | def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01):
"""Loads exampls from the tsv file.
Args:
tmp_dir: temp directory.
prop_train: proportion of the train data
prop_val: proportion of the validation data
Returns:
All examples in the dataset pluse train, test, and development splits.
"... |
Download and extract CIFAR to directory unless it is there. | def _get_cifar(directory, url):
"""Download and extract CIFAR to directory unless it is there."""
filename = os.path.basename(url)
path = generator_utils.maybe_download(directory, filename, url)
tarfile.open(path, "r:gz").extractall(directory) |
Image generator for CIFAR - 10 and 100. | def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0):
"""Image generator for CIFAR-10 and 100.
Args:
cifar_version: string; one of "cifar10" or "cifar100"
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set, otherwise the test set.
... |
HParams for PPO base. | def rlmb_ppo_base():
"""HParams for 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 simultaneous... |
rlmb_dqn_base params. | def rlmb_dqn_base():
"""rlmb_dqn_base params."""
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_... |
Base setting but quicker with only 2 epochs. | def rlmb_ppo_quick():
"""Base setting but quicker with only 2 epochs."""
hparams = rlmb_ppo_base()
hparams.epochs = 2
hparams.model_train_steps = 25000
hparams.ppo_epochs_num = 700
hparams.ppo_epoch_length = 50
return hparams |
Base setting with a stochastic next - frame model. | def rlmb_base_stochastic():
"""Base setting with a stochastic next-frame model."""
hparams = rlmb_base()
hparams.initial_epoch_train_steps_multiplier = 5
hparams.generative_model = "next_frame_basic_stochastic"
hparams.generative_model_params = "next_frame_basic_stochastic"
return hparams |
Base setting with stochastic discrete model. | def rlmb_base_stochastic_discrete():
"""Base setting with stochastic discrete model."""
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"
... |
Long setting with stochastic discrete model & deterministic sim starts. | def rlmb_long_stochastic_discrete_simulation_deterministic_starts():
"""Long setting with stochastic discrete model & deterministic sim starts."""
hparams = rlmb_base_stochastic_discrete()
hparams.generative_model_params = "next_frame_basic_stochastic_discrete_long"
hparams.ppo_epochs_num = 1000
hparams.simul... |
Long setting with stochastic discrete model changed ppo steps. | def rlmb_long_stochastic_discrete_100steps():
"""Long setting with stochastic discrete model, changed ppo steps."""
hparams = rlmb_long_stochastic_discrete()
hparams.ppo_epoch_length = 100
hparams.simulated_rollout_length = 100
hparams.simulated_batch_size = 8
return hparams |
Long setting with stochastic discrete model changed ppo steps. | def rlmb_long_stochastic_discrete_25steps():
"""Long setting with stochastic discrete model, changed ppo steps."""
hparams = rlmb_long_stochastic_discrete()
hparams.ppo_epoch_length = 25
hparams.simulated_rollout_length = 25
hparams.simulated_batch_size = 32
return hparams |
Base setting with stochastic discrete model. | def rlmb_base_stochastic_discrete_noresize():
"""Base setting with stochastic discrete model."""
hparams = rlmb_base()
hparams.generative_model = "next_frame_basic_stochastic_discrete"
hparams.generative_model_params = "next_frame_basic_stochastic_discrete"
hparams.resize_height_factor = 1
hparams.resize_wi... |
Base setting with sv2p as world model. | def rlmb_base_sv2p():
"""Base setting with sv2p as world model."""
hparams = rlmb_base()
hparams.learning_rate_bump = 1.0
hparams.generative_model = "next_frame_sv2p"
hparams.generative_model_params = "next_frame_sv2p_atari"
return hparams |
Parameters to override for tiny setting excluding agent - related hparams. | def _rlmb_tiny_overrides():
"""Parameters to override for tiny setting excluding agent-related hparams."""
return dict(
epochs=1,
num_real_env_frames=128,
model_train_steps=2,
max_num_noops=1,
eval_max_num_noops=1,
generative_model_params="next_frame_tiny",
stop_loop_early=... |
Tiny set for testing. | def rlmb_ppo_tiny():
"""Tiny set for testing."""
hparams = rlmb_ppo_base()
hparams = hparams.override_from_dict(_rlmb_tiny_overrides())
update_hparams(hparams, dict(
ppo_epochs_num=2,
ppo_epoch_length=10,
real_ppo_epoch_length=36,
real_ppo_effective_num_agents=2,
real_batch_size=1,... |
Tiny set for testing. | def rlmb_dqn_tiny():
"""Tiny set for testing."""
hparams = rlmb_dqn_base()
hparams = hparams.override_from_dict(_rlmb_tiny_overrides())
update_hparams(hparams, dict(
simulated_rollout_length=2,
dqn_time_limit=2,
dqn_num_frames=128,
real_dqn_replay_buffer_replay_capacity=100,
dqn_re... |
Tiny setting with a stochastic next - frame model. | def rlmb_tiny_stochastic():
"""Tiny setting with a stochastic next-frame model."""
hparams = rlmb_ppo_tiny()
hparams.epochs = 1 # Too slow with 2 for regular runs.
hparams.generative_model = "next_frame_basic_stochastic"
hparams.generative_model_params = "next_frame_basic_stochastic"
return hparams |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.