INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Tiny DQN params. | def rlmf_dqn_tiny():
"""Tiny DQN params."""
hparams = rlmf_original()
hparams = hparams.override_from_dict(rlmf_tiny_overrides())
hparams.batch_size = 1
hparams.base_algo = "dqn"
hparams.base_algo_params = "dqn_original_params"
hparams.add_hparam("dqn_num_frames", 128)
hparams.add_hparam("dqn_save_every... |
Eval set of hparams for model-free PPO. | def rlmf_eval():
"""Eval set of hparams for model-free PPO."""
hparams = rlmf_original()
hparams.batch_size = 8
hparams.eval_sampling_temps = [0.0, 0.5, 1.0]
hparams.eval_rl_env_max_episode_steps = -1
hparams.add_hparam("ppo_epoch_length", 128)
hparams.add_hparam("ppo_optimization_batch_size", 32)
hpara... |
Feed-forward Gaussian. | def feed_forward_gaussian_fun(action_space, config, observations):
"""Feed-forward Gaussian."""
if not isinstance(action_space, gym.spaces.box.Box):
raise ValueError("Expecting continuous action space.")
mean_weights_initializer = tf.initializers.variance_scaling(
scale=config.init_mean_factor)
logst... |
Curvature range.
Returns:
h_max_t, h_min_t ops | def _curvature_range(self):
"""Curvature range.
Returns:
h_max_t, h_min_t ops
"""
self._curv_win = tf.get_variable("curv_win",
dtype=tf.float32,
trainable=False,
shape=[self.curvature_wi... |
Estimate of gradient Variance.
Returns:
C_t ops. | def _grad_variance(self):
"""Estimate of gradient Variance.
Returns:
C_t ops.
"""
grad_var_ops = []
tensor_to_avg = []
for t, g in zip(self._vars, self._grad):
if isinstance(g, tf.IndexedSlices):
tensor_to_avg.append(
tf.reshape(tf.unsorted_segment_sum(g.values,
... |
Distance to optimum.
Returns:
D_t ops | def _dist_to_opt(self):
"""Distance to optimum.
Returns:
D_t ops
"""
dist_to_opt_ops = []
# Running average of the norm of gradient
self._grad_norm = tf.sqrt(self._grad_norm_squared)
avg_op = self._moving_averager.apply([self._grad_norm,])
dist_to_opt_ops.append(avg_op)
with t... |
Gradient sparsity. | def _grad_sparsity(self):
"""Gradient sparsity."""
# If the sparse minibatch gradient has 10 percent of its entries
# non-zero, its sparsity is 0.1.
# The norm of dense gradient averaged from full dataset
# are roughly estimated norm of minibatch
# sparse gradient norm * sqrt(sparsity)
# An ... |
Prepare Variables for YellowFin.
Returns:
Grad**2, Norm, Norm**2, Mean(Norm**2) ops | def _prepare_variables(self):
"""Prepare Variables for YellowFin.
Returns:
Grad**2, Norm, Norm**2, Mean(Norm**2) ops
"""
self._moving_averager = tf.train.ExponentialMovingAverage(
decay=self._beta, zero_debias=self._zero_debias)
# assert self._grad is not None and len(self._grad) > 0
... |
Get the cubic root. | def _get_cubic_root(self):
"""Get the cubic root."""
# We have the equation x^2 D^2 + (1-x)^4 * C / h_min^2
# where x = sqrt(mu).
# We substitute x, which is sqrt(mu), with x = y + 1.
# It gives y^3 + py = q
# where p = (D^2 h_min^2)/(2*C) and q = -p.
# We use the Vieta's substitution to com... |
Get lr minimizing the surrogate.
Returns:
The lr_t. | def _get_lr_tensor(self):
"""Get lr minimizing the surrogate.
Returns:
The lr_t.
"""
lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min
return lr |
Get the min mu which minimize the surrogate.
Returns:
The mu_t. | def _get_mu_tensor(self):
"""Get the min mu which minimize the surrogate.
Returns:
The mu_t.
"""
root = self._get_cubic_root()
dr = self._h_max / self._h_min
mu = tf.maximum(
root**2, ((tf.sqrt(dr) - 1) / (tf.sqrt(dr) + 1))**2)
return mu |
YellowFin auto-tuning optimizer based on momentum SGD.
Returns:
YF ops
(Curvature range,
Grad_variance,
Dist_to_opt,
Single-Step,
Auto-Tuning) | def _yellowfin(self):
"""YellowFin auto-tuning optimizer based on momentum SGD.
Returns:
YF ops
(Curvature range,
Grad_variance,
Dist_to_opt,
Single-Step,
Auto-Tuning)
"""
# List for the returned Operations.
yellowfin_ops = []
# Curvature range... |
Applying gradients and tune hyperparams with YellowFin.
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
compute_gradients().
global_step: Optional Variable to increment by one after the
variables have been updated.
name: Optional name for the returned oper... | def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""Applying gradients and tune hyperparams with YellowFin.
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
compute_gradients().
global_step: Optional Variable to increment by one after the
... |
Compute gradients through momentum optimizer.
Args:
loss: A Tensor containing the value to minimize.
var_list: Optional list or tuple of tf.Variable to update
to minimize loss. Defaults to the list of variables collected
in the graph under the key GraphKey.TRAINABLE_VARIABLES.
glo... | def compute_gradients(self,
loss,
var_list,
global_step=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=N... |
Adapted from TensorFlow Optimizer base class member function.
Add operations to minimize `loss` by updating `var_list`.
This method simply combines calls `compute_gradients()` and
`apply_gradients()`. If you want to process the gradient before applying
them call `tf.gradients()` and `self.apply_gradien... | def minimize(self,
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None):
"""Adapted from TensorFlow... |
A stack of convolution blocks with residual connections. | def residual_dilated_conv(x, repeat, padding, name, hparams):
"""A stack of convolution blocks with residual connections."""
with tf.variable_scope(name):
k = (hparams.kernel_height, hparams.kernel_width)
dilations_and_kernels = [((2**i, 1), k)
for i in range(hparams.num_hidden_... |
ByteNet, main step used for training. | def bytenet_internal(inputs, targets, hparams):
"""ByteNet, main step used for training."""
with tf.variable_scope("bytenet"):
# Flatten inputs and extend length by 50%.
inputs = tf.expand_dims(common_layers.flatten4d3d(inputs), axis=2)
extend_length = tf.to_int32(0.5 * tf.to_float(tf.shape(inputs)[1]))... |
Set of hyperparameters. | def bytenet_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 2048
hparams.hidden_size = 768
hparams.dropout = 0.2
hparams.symbol_dropout = 0.2
hparams.label_smoothing = 0.1
hparams.clip_grad_norm = 2.0
hparams.num_hidden_layers = 4
hparams.kernel_he... |
Downloads and prepairs the dataset to be parsed by the data_generator. | def _download_and_parse_dataset(tmp_dir, train):
"""Downloads and prepairs the dataset to be parsed by the data_generator."""
file_path = generator_utils.maybe_download(tmp_dir, _SNLI_ZIP, _SNLI_URL)
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(tmp_dir)
zip_ref.close()
file_name = 'train' i... |
Parse str to tokens and pos tags. | def _get_tokens_and_tags(parse_str):
"""Parse str to tokens and pos tags."""
tokens = []
parse_split = parse_str.split(' ')
for p in parse_split:
assert p.startswith('(') or p.endswith(')')
if p.endswith(')'):
token = p.replace(')', '')
tokens.append(token)
return tokens |
Convert the dataset in to a simpler format.
This function creates two files. One for being processed to produce a vocab
and another to generate the data.
Args:
file_path: string, path to the file to parse.
tmp_dir: string, path to the directory to output the files.
train: bool, indicating if we are ... | def _parse_dataset(file_path, tmp_dir, train):
"""Convert the dataset in to a simpler format.
This function creates two files. One for being processed to produce a vocab
and another to generate the data.
Args:
file_path: string, path to the file to parse.
tmp_dir: string, path to the directory to outp... |
Read or create vocabulary. | def _get_or_generate_vocab(tmp_dir, vocab_filename, vocab_size):
"""Read or create vocabulary."""
vocab_filepath = os.path.join(tmp_dir, vocab_filename)
print('Vocab file written to: ' + vocab_filepath)
if tf.gfile.Exists(vocab_filepath):
gs = text_encoder.SubwordTextEncoder(vocab_filepath)
return gs
... |
Generate example dicts. | def snli_token_generator(tmp_dir, train, vocab_size):
"""Generate example dicts."""
_download_and_parse_dataset(tmp_dir, train)
symbolizer_vocab = _get_or_generate_vocab(
tmp_dir, 'vocab.subword_text_encoder', vocab_size)
file_name = 'train' if train else 'dev'
data_file = os.path.join(tmp_dir, file_n... |
Split items into num_shards groups. | def shard(items, num_shards):
"""Split items into num_shards groups."""
sharded = []
num_per_shard = len(items) // num_shards
start = 0
for _ in range(num_shards):
sharded.append(items[start:start + num_per_shard])
start += num_per_shard
remainder = len(items) % num_shards
start = len(items) - re... |
An initializer function for random normal coefficients. | def RandomNormalInitializer(stddev=1e-2):
"""An initializer function for random normal coefficients."""
def init(shape, rng):
return (stddev * backend.random.normal(rng, shape)).astype('float32')
return init |
An initializer function for random Glorot-scaled coefficients. | def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)):
"""An initializer function for random Glorot-scaled coefficients."""
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
size = onp.prod(onp.delete(shape, [in_dim, out_dim]))
std = scale / np.sqrt((fan_in + fan_out) /... |
An initializer function for random uniform Glorot-scaled coefficients. | def GlorotUniformInitializer(out_dim=0, in_dim=1):
"""An initializer function for random uniform Glorot-scaled coefficients."""
def init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
std = np.sqrt(2.0 / (fan_in + fan_out))
a = np.sqrt(3.0) * std
return backend.random.uniform(rng, shap... |
Make a n+1 dim one-hot array from n dim int-categorical array. | def one_hot(x, size, dtype=np.float32):
"""Make a n+1 dim one-hot array from n dim int-categorical array."""
return np.array(x[..., np.newaxis] == np.arange(size), dtype) |
Apply log softmax to x: log-normalize along the given axis. | def LogSoftmax(x, params, axis=-1, **kwargs):
"""Apply log softmax to x: log-normalize along the given axis."""
del params, kwargs
return x - backend.logsumexp(x, axis, keepdims=True) |
Apply softmax to x: exponentiate and normalize along the given axis. | def Softmax(x, params, axis=-1, **kwargs):
"""Apply softmax to x: exponentiate and normalize along the given axis."""
del params, kwargs
return np.exp(x - backend.logsumexp(x, axis, keepdims=True)) |
Convert padding string to list of pairs of pad values. | def padtype_to_pads(in_shape, window_shape, window_strides, padding):
"""Convert padding string to list of pairs of pad values."""
padding = padding.upper()
if padding == 'SAME':
out_shape = onp.ceil(
onp.true_divide(in_shape, window_strides)).astype(int)
pad_sizes = [max((out_size - 1) * stride +... |
Output shape of a flatten layer. | def _flatten_output_shape(input_shape, num_axis_to_keep=1):
"""Output shape of a flatten layer."""
if num_axis_to_keep >= len(input_shape):
raise ValueError(
"num_axis_to_keep[%d] should be less than input's rank[%d]" %
(num_axis_to_keep, len(input_shape)))
return tuple(input_shape[:num_axis_t... |
Helper to initialize batch norm params. | def _batch_norm_new_params(input_shape, rng, axis=(0, 1, 2),
center=True, scale=True, **kwargs):
"""Helper to initialize batch norm params."""
del rng, kwargs
axis = (axis,) if np.isscalar(axis) else axis
shape = tuple(d for i, d in enumerate(input_shape) if i not in axis)
beta = np... |
Layer construction function for a batch normalization layer. | def BatchNorm(x, params, axis=(0, 1, 2), epsilon=1e-5,
center=True, scale=True, **unused_kwargs):
"""Layer construction function for a batch normalization layer."""
mean = np.mean(x, axis, keepdims=True)
# Fast but less numerically-stable variance calculation than np.var.
m1 = np.mean(x**2, axis, ... |
Helper: compute the output shape for the pooling layer. | def _pooling_output_shape(input_shape, pool_size=(2, 2),
strides=None, padding='VALID'):
"""Helper: compute the output shape for the pooling layer."""
dims = (1,) + pool_size + (1,) # NHWC
spatial_strides = strides or (1,) * len(pool_size)
strides = (1,) + spatial_strides + (1,)
pad... |
Helper: general pooling computation used in pooling layers later. | def _pooling_general(inputs, reducer, init_val, rescaler=None,
pool_size=(2, 2), strides=None, padding='VALID'):
"""Helper: general pooling computation used in pooling layers later."""
spatial_strides = strides or (1,) * len(pool_size)
rescale = rescaler(pool_size, spatial_strides, padding) i... |
Layer construction function for a dropout layer with given rate. | def Dropout(x, params, rate=0.0, mode='train', rng=None, **kwargs):
"""Layer construction function for a dropout layer with given rate."""
del params, kwargs
if rng is None:
msg = ('Dropout layer requires apply_fun to be called with a rng keyword '
'argument. That is, instead of `Dropout(params, in... |
Helper to calculate the kernel shape. | def _kernel_shape(self, input_shape):
"""Helper to calculate the kernel shape."""
kernel_size_iter = iter(self._kernel_size)
return [self._filters if c == 'O' else
input_shape[self._lhs_spec.index('C')] if c == 'I' else
next(kernel_size_iter) for c in self._rhs_spec] |
Compute the shape of a conv given input shapes in canonical order. | def _conv_shape_tuple(self, lhs_shape, rhs_shape, strides, pads):
"""Compute the shape of a conv given input shapes in canonical order."""
if isinstance(pads, str):
pads = padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads)
if len(pads) != len(lhs_shape) - 2:
msg = 'Wrong number of expl... |
Utility for convolution dimension permutations relative to Conv HLO. | def _conv_general_permutations(self, dimension_numbers):
"""Utility for convolution dimension permutations relative to Conv HLO."""
lhs_spec, rhs_spec, out_spec = dimension_numbers
lhs_char, rhs_char, out_char = ('N', 'C'), ('O', 'I'), ('N', 'C')
charpairs = (lhs_char, rhs_char, out_char)
for i, (a,... |
Generalized computation of conv shape. | def _conv_general_shape_tuple(self, lhs_shape, rhs_shape, window_strides,
padding, dimension_numbers):
"""Generalized computation of conv shape."""
lhs_perm, rhs_perm, out_perm = self._conv_general_permutations(
dimension_numbers)
lhs_trans = onp.take(lhs_shape, lhs_p... |
Factory for dopamine agent initialization.
Args:
agent_kwargs: dict of BatchDQNAgent parameters
Returns:
Function(sess, environment, summary_writer) -> BatchDQNAgent instance. | def get_create_agent(agent_kwargs):
"""Factory for dopamine agent initialization.
Args:
agent_kwargs: dict of BatchDQNAgent parameters
Returns:
Function(sess, environment, summary_writer) -> BatchDQNAgent instance.
"""
def create_agent(sess, environment, summary_writer=None):
"""Creates a DQN a... |
Factory for dopamine environment initialization function.
Args:
batch_env_fn: function(in_graph: bool) -> batch environment.
time_limit: time steps limit for environment.
Returns:
function (with optional, unused parameters) initializing environment. | def get_create_batch_env_fun(batch_env_fn, time_limit):
"""Factory for dopamine environment initialization function.
Args:
batch_env_fn: function(in_graph: bool) -> batch environment.
time_limit: time steps limit for environment.
Returns:
function (with optional, unused parameters) initializing envi... |
Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. | def _parse_hparams(hparams):
"""Split hparams, based on key prefixes.
Args:
hparams: hyperparameters
Returns:
Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
"""
prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"]
ret = []
for prefix in prefixes:
ret_... |
Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer. | def _build_replay_buffer(self, use_staging):
"""Build WrappedReplayBuffer with custom OutOfGraphReplayBuffer."""
replay_buffer_kwargs = dict(
observation_shape=dqn_agent.NATURE_DQN_OBSERVATION_SHAPE,
stack_size=dqn_agent.NATURE_DQN_STACK_SIZE,
replay_capacity=self._replay_capacity,
... |
Append artificial_done to *args and run parent method. | def add(self, observation, action, reward, terminal, *args):
"""Append artificial_done to *args and run parent method."""
# If this will be a problem for maintenance, we could probably override
# DQNAgent.add() method instead.
artificial_done = self._artificial_done and terminal
args = list(args)
... |
Step. | def step(self, actions):
"""Step."""
self._elapsed_steps += 1
obs, rewards, dones = \
[np.array(r) for r in self.batch_env.step(actions)]
if self._elapsed_steps > self._max_episode_steps:
done = True
if self._elapsed_steps > self._max_episode_steps + 1:
rewards.fill(0)
el... |
Set of hyperparameters. | def text_cnn_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 4096
hparams.max_length = 256
hparams.clip_grad_norm = 0. # i.e. no gradient clipping
hparams.optimizer_adam_epsilon = 1e-9
hparams.learning_rate_schedule = "legacy"
hparams.learning_rate_de... |
Hparams for next_frame_glow. | def next_frame_glow_hparams():
"""Hparams for next_frame_glow."""
hparams = glow.glow_hparams()
# Possible modes are conditional and unconditional
hparams.add_hparam("gen_mode", "conditional")
hparams.add_hparam("learn_top_scale", False)
hparams.add_hparam("condition_all_levels", True)
# For each video, s... |
Hparams to reproduce bits-per-pixel results on BAIR action-free dataset. | def next_frame_glow_bair_quant():
"""Hparams to reproduce bits-per-pixel results on BAIR action-free dataset."""
hparams = next_frame_glow_hparams()
hparams.video_num_input_frames = 3
hparams.video_num_target_frames = 10
hparams.num_train_frames = 4
hparams.num_cond_latents = 3
hparams.depth = 24
hparam... |
Hparams for qualitative video generation results. | def next_frame_glow_bair_qual():
"""Hparams for qualitative video generation results."""
hparams = next_frame_glow_bair_quant()
hparams.coupling = "additive"
hparams.temperature = 0.5
hparams.coupling_width = 392
return hparams |
Hparams for qualitative and quantitative results on shapes dataset. | def next_frame_glow_shapes():
"""Hparams for qualitative and quantitative results on shapes dataset."""
hparams = next_frame_glow_bair_quant()
hparams.video_num_input_frames = 1
hparams.video_num_target_frames = 2
hparams.num_train_frames = 2
hparams.num_cond_latents = 1
hparams.coupling = "additive"
hp... |
Get z^{cond}_{t} given z^{1..t-1}.
Args:
all_latents: list of list of tensors,
outer-size equals no.of time_steps-1
inner-size equals hparams.n_levels.
hparams: See next_frame_glow_hparams.
Returns:
cond_latents: conditional latents at time-step t. | def get_cond_latents(all_latents=None, hparams=None):
"""Get z^{cond}_{t} given z^{1..t-1}.
Args:
all_latents: list of list of tensors,
outer-size equals no.of time_steps-1
inner-size equals hparams.n_levels.
hparams: See next_frame_glow_hparams.
Returns:
cond_latent... |
Small fully connected model. | def basic_fc_small():
"""Small fully connected model."""
hparams = common_hparams.basic_params1()
hparams.learning_rate = 0.1
hparams.batch_size = 128
hparams.hidden_size = 256
hparams.num_hidden_layers = 2
hparams.initializer = "uniform_unit_scaling"
hparams.initializer_gain = 1.0
hparams.weight_deca... |
A stack of layers.
Args:
mp: a Parallelism object
inputs: a list of Tensors
self_attention_bias: list of bias Tensor for self-attention
(see common_attention.attention_bias())
layers: a string
hparams: hyperparameters for model
encoder_output: optional list of tensors
encoder_decode... | def _layer_stack(mp,
inputs,
self_attention_bias,
layers,
hparams,
encoder_output=None,
encoder_decoder_attention_bias=None):
"""A stack of layers.
Args:
mp: a Parallelism object
inputs: a list of Tensors
... |
Set of hyperparameters. | def transformer_symshard_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.hidden_size = 256
hparams.batch_size = 2048
hparams.max_length = 0
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
hparams.layer_prepostproc... |
Image generator for Imagenet 64x64 downsampled images.
It assumes that the data has been downloaded from
http://image-net.org/small/*_32x32.tar or
http://image-net.org/small/*_64x64.tar into tmp_dir.
Args:
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set,... | def imagenet_pixelrnn_generator(tmp_dir,
training,
size=_IMAGENET_SMALL_IMAGE_SIZE):
"""Image generator for Imagenet 64x64 downsampled images.
It assumes that the data has been downloaded from
http://image-net.org/small/*_32x32.tar or
http://image... |
Preprocessing used for Imagenet and similar problems. | def imagenet_preprocess_example(example, mode, resize_size=None,
normalize=True):
"""Preprocessing used for Imagenet and similar problems."""
resize_size = resize_size or [299, 299]
assert resize_size[0] == resize_size[1]
image = example["inputs"]
if mode == tf.estimator.ModeK... |
Crops the given image using the provided offsets and sizes.
Note that the method doesn't assume we know the input image size but it does
assume we know the input image rank.
Args:
image: `Tensor` image of shape [height, width, channels].
offset_height: `Tensor` indicating the height offset.
offset_w... | def _crop(image, offset_height, offset_width, crop_height, crop_width):
"""Crops the given image using the provided offsets and sizes.
Note that the method doesn't assume we know the input image size but it does
assume we know the input image rank.
Args:
image: `Tensor` image of shape [height, width, chan... |
Generates cropped_image using a one of the bboxes randomly distorted.
See `tf.image.sample_distorted_bounding_box` for more documentation.
Args:
image: `Tensor` of image (it will be converted to floats in [0, 1]).
bbox: `Tensor` of bounding boxes arranged `[1, num_boxes, coords]`
where each coordi... | def distorted_bounding_box_crop(image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0),
max_attempts=100,
... |
Make a random crop of (`size` x `size`). | def _random_crop(image, size):
"""Make a random crop of (`size` x `size`)."""
bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
random_image, bbox = distorted_bounding_box_crop(
image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(3. / 4, 4. / 3.),
area_... |
At least `x` of `a` and `b` `Tensors` are true. | def _at_least_x_are_true(a, b, x):
"""At least `x` of `a` and `b` `Tensors` are true."""
match = tf.equal(a, b)
match = tf.cast(match, tf.int32)
return tf.greater_equal(tf.reduce_sum(match), x) |
Rescale the image by scaling the smaller spatial dimension to `size`. | def _do_scale(image, size):
"""Rescale the image by scaling the smaller spatial dimension to `size`."""
shape = tf.cast(tf.shape(image), tf.float32)
w_greater = tf.greater(shape[0], shape[1])
shape = tf.cond(w_greater,
lambda: tf.cast([shape[0] / shape[1] * size, size], tf.int32),
... |
Crops to center of image with specified `size`. | def _center_crop(image, size):
"""Crops to center of image with specified `size`."""
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
offset_height = ((image_height - size) + 1) / 2
offset_width = ((image_width - size) + 1) / 2
image = _crop(image, offset_height, offset_width, size, size)... |
Normalize the image to zero mean and unit variance. | def _normalize(image):
"""Normalize the image to zero mean and unit variance."""
offset = tf.constant(MEAN_RGB, shape=[1, 1, 3])
image -= offset
scale = tf.constant(STDDEV_RGB, shape=[1, 1, 3])
image /= scale
return image |
Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A preprocessed image `Tensor`. | def preprocess_for_train(image, image_size=224, normalize=True):
"""Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A prep... |
Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A preprocessed image `Tensor`. | def preprocess_for_eval(image, image_size=224, normalize=True):
"""Preprocesses the given image for evaluation.
Args:
image: `Tensor` representing an image of arbitrary size.
image_size: int, how large the output image should be.
normalize: bool, if True the image is normalized.
Returns:
A prepr... |
Learning rate that decreases when eval metric stalls.
If the chosen metric does not improve by improvement_margin for as many as
steps_to_decrease steps, then the constant gets decreased by decrease rate.
Finally, the MultifactorSchedule gets called with the adjusted constant.
Args:
history: trax.history.... | def EvalAdjustingSchedule(history,
constant=0.1,
steps_to_decrease=20,
improvement_margin=0.001,
decrease_rate=1.5,
history_mode="eval",
metric="metrics/accuracy"):... |
Factor-based learning rate schedule.
Interprets factors in the factors string which can consist of:
* constant: interpreted as the constant value,
* linear_warmup: interpreted as linear warmup until warmup_steps,
* rsqrt_decay: divide by square root of max(step, warmup_steps)
* decay_every: Every k steps dec... | def MultifactorSchedule(history=None,
factors="constant * linear_warmup * rsqrt_decay",
constant=0.1,
warmup_steps=100,
decay_factor=0.5,
steps_per_decay=20000):
"""Factor-based learning rate schedu... |
Project encoder hidden state under num_blocks using projection tensors.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
projection_tensors: Projection tensors used to project the hidden state.
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in D... | def project_hidden(x, projection_tensors, hidden_size, num_blocks):
"""Project encoder hidden state under num_blocks using projection tensors.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
projection_tensors: Projection tensors used to project the hidden state.
hidden_s... |
Slice encoder hidden state under num_blocks.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in DVQ.
Returns:
Sliced states of shape [batch_size, latent_dim, num_blocks, block_dim]. | def slice_hidden(x, hidden_size, num_blocks):
"""Slice encoder hidden state under num_blocks.
Args:
x: Encoder hidden state of shape [batch_size, latent_dim, hidden_size].
hidden_size: Dimension of the latent space.
num_blocks: Number of blocks in DVQ.
Returns:
Sliced states of shape [batch_size... |
Find the nearest element in means to elements in x.
Args:
x: Continuous encodings of shape [batch_size, latent_dim, num_blocks,
block_dim].
means: Embedding table of shape [num_blocks, block_v_size, block_dim].
block_v_size: Number of table entries per block.
random_top_k: Noisy top-k if this i... | def nearest_neighbor(x,
means,
block_v_size,
random_top_k=1,
soft_em=False,
num_samples=1,
sum_over_latents=False,
summary=True):
"""Find the nearest element in means to e... |
Turn x_bit representing numbers bitwise (lower-endian) to int tensor.
Args:
x_bit: Tensor containing numbers in a particular base to be converted to
int.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
Integer representation of this number. | def bit_to_int(x_bit, num_bits, base=2):
"""Turn x_bit representing numbers bitwise (lower-endian) to int tensor.
Args:
x_bit: Tensor containing numbers in a particular base to be converted to
int.
num_bits: Number of bits in the representation.
base: Base of the representation.
Returns:
I... |
Compute nearest neighbors and loss for training the embeddings via DVQ.
Args:
x: Continuous encodings of shape [batch_size, latent_dim, num_blocks,
block_dim].
means: Embedding table of shape [num_blocks, block_v_size, block_dim].
num_blocks: Number of blocks in DVQ.
block_v_size: Number of tab... | def embedding_lookup(x,
means,
num_blocks,
block_v_size,
bottleneck_kind="dvq",
random_top_k=1,
soft_em=False,
num_samples=1,
do_hard_gumbel_softmax=Fal... |
Turn x_int into a bitwise (lower-endian) tensor and embed densly. | def int_to_bit_embed(x_int, num_bits, embedding_size, base=2):
"""Turn x_int into a bitwise (lower-endian) tensor and embed densly."""
shape = common_layers.shape_list(x_int)
inputs = int_to_bit(x_int, num_bits, base=base)
inputs = tf.reshape(inputs, shape[:-1] + [shape[-1] * 8])
inputs = 2.0 * tf.to_float(in... |
Embedding function that takes discrete latent and returns embedding.
Args:
x: Input to the discretization bottleneck.
hidden_size: Dimension of the latent state.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
filter_size: Dimension to project embedding by. Used only if bottle... | def embed(x,
hidden_size,
z_size,
filter_size,
bottleneck_kind="dvq",
soft_em=False,
num_blocks=2,
num_residuals=1,
block_v_size=None,
means=None,
name=None):
"""Embedding function that takes discrete latent and return... |
Simple variational autoencoder without discretization.
Args:
x: Input to the discretization bottleneck.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
name: Name for the bottleneck scope.
Returns:
Embedding function, latent, loss, mu and log_simga. | def vae(x, z_size, name=None):
"""Simple variational autoencoder without discretization.
Args:
x: Input to the discretization bottleneck.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
name: Name for the bottleneck scope.
Returns:
Embedding function, latent, loss, mu and... |
Sample from the Gumbel distribution, protect from overflows.
Args:
shape: Shape of Gumbel samples.
Returns:
Noise drawn from Gumbel distribution. | def gumbel_sample(shape):
"""Sample from the Gumbel distribution, protect from overflows.
Args:
shape: Shape of Gumbel samples.
Returns:
Noise drawn from Gumbel distribution.
"""
uniform_samples = tf.random_uniform(shape, minval=0.00001, maxval=0.99998)
return -tf.log(-tf.log(uniform_samples)) |
Gumbel softmax discretization bottleneck.
Args:
x: Input to the discretization bottleneck.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
mode: tf.estimator.ModeKeys.
softmax_k: If > 0 then do top-k softmax.
temperature_warmup_steps: Number of steps it takes to decay temp... | def gumbel_softmax(x,
z_size,
mode,
softmax_k=0,
temperature_warmup_steps=150000,
summary=True,
name=None):
"""Gumbel softmax discretization bottleneck.
Args:
x: Input to the discretization bottlen... |
Discretization bottleneck.
Args:
inputs: Input to the bottleneck, a Tensor of shape [..., channels].
hidden_size: Dimension of the dense output.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
filter_size: Filter size in the embedding function.
mode: tf.estimator.ModeKeys.... | def discrete_bottleneck(inputs,
hidden_size,
z_size,
filter_size,
mode=None,
bottleneck_kind="dvq",
num_blocks=2,
num_residuals=1,
... |
Predict a sequence of bits (a latent) with LSTM, both training and infer.
Given a tensor on which the predictions are based (prediction_source), we use
a single-layer LSTM with state of size state_size to predict total_num_bits,
which we predict in groups of size bits_at_once. During training, we use
target_bi... | def predict_bits_with_lstm(prediction_source, state_size, total_num_bits,
target_bits=None, extra_inputs=None,
bits_at_once=8, temperature=1.0, dropout=0.1):
"""Predict a sequence of bits (a latent) with LSTM, both training and infer.
Given a tensor on which th... |
Get lookup table for VQ bottleneck. | def get_vq_codebook(codebook_size, hidden_size):
"""Get lookup table for VQ bottleneck."""
with tf.variable_scope("vq", reuse=tf.AUTO_REUSE):
means = tf.get_variable(
name="means",
shape=[codebook_size, hidden_size],
initializer=tf.uniform_unit_scaling_initializer())
ema_count = tf.... |
Find the nearest element in means to elements in x. | def vq_nearest_neighbor(x, means,
soft_em=False, num_samples=10, temperature=None):
"""Find the nearest element in means to elements in x."""
bottleneck_size = common_layers.shape_list(means)[0]
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum... |
Simple vector quantized discrete bottleneck. | def vq_discrete_bottleneck(x,
bottleneck_bits,
beta=0.25,
decay=0.999,
epsilon=1e-5,
soft_em=False,
num_samples=10):
"""Simple vector quantized discrete bot... |
Discretize each x into one of codebook_size codes. | def vq_body(x,
codebook_size,
beta=0.25,
decay=0.999,
epsilon=1e-5,
soft_em=False,
num_samples=10,
temperature=None,
do_update=True):
"""Discretize each x into one of codebook_size codes."""
x_shape = common_layers.shape... |
Compute the loss of large vocab tensors using a VQAE codebook.
Args:
x: Tensor of inputs to be quantized to nearest code
targets: Tensor of target indices to target codes
codebook_size: Size of quantization codebook
beta: scalar float for moving averages
decay: scalar float for moving averages
... | def vq_loss(x,
targets,
codebook_size,
beta=0.25,
decay=0.999,
epsilon=1e-5,
soft_em=False,
num_samples=10,
temperature=None,
do_update=True):
"""Compute the loss of large vocab tensors using a VQAE codebook.
... |
Simple undiscretization from vector quantized representation. | def vq_discrete_unbottleneck(x, hidden_size):
"""Simple undiscretization from vector quantized representation."""
x_shape = common_layers.shape_list(x)
x = tf.to_float(x)
bottleneck_size = common_layers.shape_list(x)[-1]
means, _, _ = get_vq_codebook(bottleneck_size, hidden_size)
result = tf.matmul(tf.resha... |
Sample from Gumbel-Softmax and compute neighbors and losses.
Args:
x: A `float`-like `Tensor` of shape [batch_size, latent_dim, num_blocks,
block_dim] containing the latent vectors to be compared to the codebook.
means: Embedding table of shape [num_blocks, block_v_size, block_dim].
block_v_size: N... | def gumbel_softmax_nearest_neighbor_dvq(x,
means,
block_v_size,
hard=False,
temperature_init=1.2,
num_samples=1,
... |
VQ-VAE using Gumbel-Softmax.
Different from `gumbel_softmax()` function as
this function calculates the KL by using the discrete entropy
instead of taking the argmax, and it also uses an exponential moving average
to update the codebook while the `gumbel_softmax()` function includes no
codebook update.
Ar... | def gumbel_softmax_discrete_bottleneck(x,
bottleneck_bits,
beta=0.25,
decay=0.999,
epsilon=1e-5,
temperature_warmup_steps=150... |
Simple un-discretization from tanh. | def tanh_discrete_unbottleneck(x, hidden_size):
"""Simple un-discretization from tanh."""
x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck")
return x |
Simple discretization through tanh, flip bottleneck_noise many bits. | def tanh_discrete_bottleneck(x, bottleneck_bits, bottleneck_noise,
discretize_warmup_steps, mode):
"""Simple discretization through tanh, flip bottleneck_noise many bits."""
x = tf.layers.dense(x, bottleneck_bits, name="tanh_discrete_bottleneck")
d0 = tf.stop_gradient(2.0 * tf.to_floa... |
Improved semantic hashing bottleneck. | def isemhash_bottleneck(x,
bottleneck_bits,
bottleneck_noise,
discretize_warmup_steps,
mode,
isemhash_noise_dev=0.5,
isemhash_mix_prob=0.5):
"""Improved semantic hashing bott... |
Improved semantic hashing un-bottleneck. | def isemhash_unbottleneck(x, hidden_size, isemhash_filter_size_multiplier=1.0):
"""Improved semantic hashing un-bottleneck."""
filter_size = int(hidden_size * isemhash_filter_size_multiplier)
x = 0.5 * (x - 1.0) # Move from [-1, 1] to [0, 1].
with tf.variable_scope("isemhash_unbottleneck"):
h1a = tf.layers... |
Meta-function calling all the above bottlenecks with hparams. | def parametrized_bottleneck(x, hparams):
"""Meta-function calling all the above bottlenecks with hparams."""
if hparams.bottleneck_kind == "tanh_discrete":
d, _ = tanh_discrete_bottleneck(
x, hparams.bottleneck_bits, hparams.bottleneck_noise * 0.5,
hparams.discretize_warmup_steps, hparams.mode)
... |
Meta-function calling all the above un-bottlenecks with hparams. | def parametrized_unbottleneck(x, hidden_size, hparams):
"""Meta-function calling all the above un-bottlenecks with hparams."""
if hparams.bottleneck_kind == "tanh_discrete":
return tanh_discrete_unbottleneck(x, hidden_size)
if hparams.bottleneck_kind == "isemhash":
return isemhash_unbottleneck(x, hidden_s... |
Create hyperpameters for inverse autoregressive flows.
Args:
hidden_size: Width of attention layers and neural network output layer.
filter_size: Hidden layer width for neural network.
Returns:
hparams: Hyperpameters with basic presets for inverse autoregressive flows. | def iaf_hparams(hidden_size=512, filter_size=4096):
"""Create hyperpameters for inverse autoregressive flows.
Args:
hidden_size: Width of attention layers and neural network output layer.
filter_size: Hidden layer width for neural network.
Returns:
hparams: Hyperpameters with basic presets for inver... |
Returns a set containing the original vocabulary.
This is important for comparing with published results.
Args:
tmp_dir: directory containing dataset.
Returns:
a set of strings | def _original_vocab(tmp_dir):
"""Returns a set containing the original vocabulary.
This is important for comparing with published results.
Args:
tmp_dir: directory containing dataset.
Returns:
a set of strings
"""
vocab_url = ("http://download.tensorflow.org/models/LM_LSTM_CNN/"
"v... |
Replace out-of-vocab words with "UNK".
This maintains compatibility with published results.
Args:
original_vocab: a set of strings (The standard vocabulary for the dataset)
line: a unicode string - a space-delimited sequence of words.
Returns:
a unicode string - a space-delimited sequence of words. | def _replace_oov(original_vocab, line):
"""Replace out-of-vocab words with "UNK".
This maintains compatibility with published results.
Args:
original_vocab: a set of strings (The standard vocabulary for the dataset)
line: a unicode string - a space-delimited sequence of words.
Returns:
a unicode ... |
Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset. | def _maybe_download_corpus(tmp_dir):
"""Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
"""
corpus_url = ("http://www.statmt.org/lm-benchmark/"
"1-billion-word-language-modeling-benchmark-r13output.tar.gz")
corpus_filename = os.path.basename(corpus_url)
corp... |
Loss function. | def lossfn(real_input, fake_input, compress, hparams, lsgan, name):
"""Loss function."""
eps = 1e-12
with tf.variable_scope(name):
d1 = discriminator(real_input, compress, hparams, "discriminator")
d2 = discriminator(fake_input, compress, hparams, "discriminator",
reuse=True)
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.