INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
Cycle GAN, main step used for training. | def cycle_gan_internal(inputs, targets, _, hparams):
"""Cycle GAN, main step used for training."""
with tf.variable_scope("cycle_gan"):
# Embed inputs and targets.
inputs_orig, targets_orig = tf.to_int32(inputs), tf.to_int32(targets)
inputs = common_layers.embedding(
inputs_orig, hparams.vocab_size, hparams.hidden_size, "embed")
targets = common_layers.embedding(
targets_orig, hparams.vocab_size, hparams.hidden_size,
"embed", reuse=True)
x, _ = split_on_batch(inputs)
_, y = split_on_batch(targets)
# Y --> X
y_fake = generator(y, hparams, "Fy", reuse=False)
y_to_x_loss = lossfn(y, y_fake, True, hparams, True, "YtoX")
# X --> Y
x_fake = generator(x, hparams, "Gx", reuse=False)
x_to_y_loss = lossfn(y, x_fake, True, hparams, True, "XtoY")
# Cycle-Consistency
y_fake_ = generator(y_fake, hparams, "Gx", reuse=True)
x_fake_ = generator(x_fake, hparams, "Fy", reuse=True)
x_to_x_loss = hparams.cycle_loss_multiplier1 * tf.reduce_mean(
tf.abs(x_fake_ - x))
y_to_y_loss = hparams.cycle_loss_multiplier2 * tf.reduce_mean(
tf.abs(y_fake_ - y))
cycloss = x_to_x_loss + y_to_y_loss
sample_generated = generator(inputs, hparams, "Gx", reuse=True)
sample_generated = tf.layers.dense(
sample_generated, hparams.vocab_size, name="softmax", reuse=None)
sample_generated = tf.stop_gradient(
tf.expand_dims(sample_generated, axis=2))
losses = {"cycloss": cycloss,
"y_to_x_loss": y_to_x_loss,
"x_to_y_loss": x_to_y_loss}
return sample_generated, losses |
Hparams for decoding. | def decode_hparams(overrides=""):
"""Hparams for decoding."""
hparams = decoding.decode_hparams()
# Number of interpolations between [0.0, 1.0].
hparams.add_hparam("num_interp", 11)
# Which level(s) to interpolate.
hparams.add_hparam("level_interp", [0, 1, 2])
# "all" or "ranked", interpolate all channels or a "ranked".
hparams.add_hparam("channel_interp", "all")
# interpolate channels ranked according to squared L2 norm.
hparams.add_hparam("rank_interp", 1)
# Whether on not to save frames as summaries
hparams.add_hparam("save_frames", True)
hparams.parse(overrides)
return hparams |
Set of hyperparameters. | def cycle_gan_small():
"""Set of hyperparameters."""
hparams = transformer_vae.transformer_ae_small()
hparams.batch_size = 2048
hparams.bottom = {
"inputs": modalities.identity_bottom,
"targets": modalities.identity_bottom,
}
hparams.top = {
"targets": modalities.identity_top,
}
hparams.weight_decay = 3.0
hparams.learning_rate = 0.05
hparams.kl_warmup_steps = 5000
hparams.learning_rate_warmup_steps = 3000
hparams.add_hparam("vocab_size", 66) # Vocabulary size, need to set here.
hparams.add_hparam("cycle_loss_multiplier1", 10.0)
hparams.add_hparam("cycle_loss_multiplier2", 10.0)
return hparams |
Preprocess frame.
1. Converts [0, 255] to [-0.5, 0.5]
2. Adds uniform noise.
Args:
frame: 3-D Tensor representing pixels.
Returns:
frame: 3-D Tensor with values in between [-0.5, 0.5] | def preprocess_frame(frame):
"""Preprocess frame.
1. Converts [0, 255] to [-0.5, 0.5]
2. Adds uniform noise.
Args:
frame: 3-D Tensor representing pixels.
Returns:
frame: 3-D Tensor with values in between [-0.5, 0.5]
"""
# Normalize from [0.0, 1.0] -> [-0.5, 0.5]
frame = common_layers.convert_rgb_to_real(frame)
frame = frame - 0.5
frame, _ = glow_ops.uniform_binning_correction(frame)
return frame |
Encode frames to latents. | def frame_to_latents(frame, hparams):
"""Encode frames to latents."""
# Preprocess
frame = preprocess_frame(frame)
# Encode [X_t] to [z^1_t, z^2_t .. z^l_t]
glow_vals = glow_ops.encoder_decoder(
"codec", frame, hparams, eps=None, reverse=False)
z_top, _, level_eps, _, _ = glow_vals
return z_top, level_eps |
Decodes latents to frames. | def latents_to_frames(z_top_interp, level_eps_interp, hparams):
"""Decodes latents to frames."""
# Decode [z^1_t, z^2_t .. z^l_t] to [X_t]
images, _, _, _ = glow_ops.encoder_decoder(
"codec", z_top_interp, hparams, eps=level_eps_interp, reverse=True)
images = glow_ops.postprocess(images)
return images |
Interpolate between the first input frame and last target frame.
Args:
features: dict of tensors
hparams: HParams, training hparams.
decode_hp: HParams, decode hparams.
Returns:
images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C)
first_frame: image, 3-D Tensor, shape=(1, H, W, C)
last_frame: image, 3-D Tensor, shape=(1, H, W, C) | def interpolate(features, hparams, decode_hp):
"""Interpolate between the first input frame and last target frame.
Args:
features: dict of tensors
hparams: HParams, training hparams.
decode_hp: HParams, decode hparams.
Returns:
images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C)
first_frame: image, 3-D Tensor, shape=(1, H, W, C)
last_frame: image, 3-D Tensor, shape=(1, H, W, C)
"""
inputs, targets = features["inputs"], features["targets"]
inputs = tf.unstack(inputs, axis=1)
targets = tf.unstack(targets, axis=1)
coeffs = np.linspace(0.0, 1.0, decode_hp.num_interp)
# (X_1, X_t) -> (z_1, z_t)
first_frame, last_frame = inputs[0], targets[-1]
first_top_z, first_level_eps = frame_to_latents(first_frame, hparams)
last_top_z, last_level_eps = frame_to_latents(last_frame, hparams)
# Interpolate latents at all levels.
first_lats = first_level_eps + [first_top_z]
last_lats = last_level_eps + [last_top_z]
interp_lats = []
lat_iterator = enumerate(zip(first_lats, last_lats))
for level_ind, (first_lat, last_lat) in lat_iterator:
if level_ind in decode_hp.level_interp:
if decode_hp.channel_interp == "all":
interp_lat = glow_ops.linear_interpolate(first_lat, last_lat, coeffs)
else:
interp_lat = glow_ops.linear_interpolate_rank(
first_lat, last_lat, coeffs, decode_hp.rank_interp)
else:
interp_lat = tf.tile(first_lat, [decode_hp.num_interp, 1, 1, 1])
interp_lats.append(interp_lat)
level_eps_interp = interp_lats[:hparams.n_levels-1]
z_top_interp = interp_lats[-1]
images = latents_to_frames(z_top_interp, level_eps_interp, hparams)
return images, first_frame, last_frame |
Get nested summaries_log_dir based on decode_hp. | def get_summaries_log_dir(decode_hp, output_dir, dataset_split):
"""Get nested summaries_log_dir based on decode_hp."""
child_dir = decode_hp.summaries_log_dir
level_dir = "".join([str(level) for level in decode_hp.level_interp])
if decode_hp.channel_interp == "all":
rank_dir = "all"
else:
rank_dir = "rank_%d" % decode_hp.rank_interp
child_dir = "%s/%s_%s" % (child_dir, level_dir, rank_dir)
if dataset_split is not None:
child_dir += "_{}".format(dataset_split)
return os.path.join(output_dir, child_dir) |
Converts interpolated frames into tf summaries.
The summaries consists of:
1. Image summary corresponding to the first frame.
2. Image summary corresponding to the last frame.
3. The interpolated frames as a gif summary.
Args:
sample_ind: int
interpolations: Numpy array, shape=(num_interp, H, W, 3)
first_frame: Numpy array, shape=(HWC)
last_frame: Numpy array, shape=(HWC)
hparams: HParams, train hparams
decode_hp: HParams, decode hparams
Returns:
summaries: list of tf Summary Values. | def interpolations_to_summary(sample_ind, interpolations, first_frame,
last_frame, hparams, decode_hp):
"""Converts interpolated frames into tf summaries.
The summaries consists of:
1. Image summary corresponding to the first frame.
2. Image summary corresponding to the last frame.
3. The interpolated frames as a gif summary.
Args:
sample_ind: int
interpolations: Numpy array, shape=(num_interp, H, W, 3)
first_frame: Numpy array, shape=(HWC)
last_frame: Numpy array, shape=(HWC)
hparams: HParams, train hparams
decode_hp: HParams, decode hparams
Returns:
summaries: list of tf Summary Values.
"""
parent_tag = "sample_%d" % sample_ind
frame_shape = hparams.problem.frame_shape
interp_shape = [hparams.batch_size, decode_hp.num_interp] + frame_shape
interpolations = np.reshape(interpolations, interp_shape)
interp_tag = "%s/interp/%s" % (parent_tag, decode_hp.channel_interp)
if decode_hp.channel_interp == "ranked":
interp_tag = "%s/rank_%d" % (interp_tag, decode_hp.rank_interp)
summaries, _ = common_video.py_gif_summary(
interp_tag, interpolations, return_summary_value=True,
max_outputs=decode_hp.max_display_outputs,
fps=decode_hp.frames_per_second)
if decode_hp.save_frames:
first_frame_summ = image_utils.image_to_tf_summary_value(
first_frame, "%s/first" % parent_tag)
last_frame_summ = image_utils.image_to_tf_summary_value(
last_frame, "%s/last" % parent_tag)
summaries.append(first_frame_summ)
summaries.append(last_frame_summ)
return summaries |
EPVA hparams. | def next_frame_epva():
"""EPVA hparams."""
hparams = basic_deterministic_params.next_frame_basic_deterministic()
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.bottom = {
"inputs": modalities.video_raw_bottom,
"targets": modalities.video_raw_targets_bottom,
}
hparams.loss = {
"targets": modalities.video_l2_raw_loss,
}
hparams.top = {
"targets": modalities.video_raw_top,
}
hparams.learning_rate_schedule = "constant"
hparams.learning_rate_constant = 1e-05
hparams.batch_size = 2
hparams.clip_grad_norm = 0.01
# TODO(msaffar): disentangle EPVA from SV2P
hparams.add_hparam("reward_prediction", False)
hparams.add_hparam("clip_pixel_values", True)
hparams.add_hparam("context_frames", 5)
hparams.add_hparam("enc_learning_rate", 1e-5)
hparams.add_hparam("enc_pred_loss_scale", 0.1)
hparams.add_hparam("enc_pred_loss_scale_delay", 6e5)
hparams.add_hparam("enc_size", 64)
hparams.add_hparam("enc_keep_prob", .65)
hparams.add_hparam("enc_pred_use_l1_loss", False)
hparams.add_hparam("enc_pred_use_l2norm", False)
hparams.add_hparam("van_learning_rate", 3e-5)
hparams.add_hparam("van_keep_prob", .9)
hparams.add_hparam("sequence_length ", 64)
hparams.add_hparam("skip_num", 2)
hparams.add_hparam("pred_noise_std", 0)
hparams.add_hparam("lstm_state_noise_stddev", 0)
return hparams |
Create slot variables for Adam with accumulated gradients. | def _create_slots(self, var_list):
"""Create slot variables for Adam with accumulated gradients."""
super(MultistepAdamOptimizer, self)._create_slots(var_list)
first_var = min(var_list, key=lambda x: x.name)
self._create_non_slot_variable(initial_value=0 if self._n == 1 else 1,
name="iter",
colocate_with=first_var)
for v in var_list:
self._zeros_slot(v, "grad_acc", self._name) |
Apply conditionally if counter is zero. | def _apply_cond(self, apply_fn, grad, var, *args, **kwargs):
"""Apply conditionally if counter is zero."""
grad_acc = self.get_slot(var, "grad_acc")
def apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs):
total_grad = (grad_acc + grad) / tf.cast(self._n_t, grad.dtype)
adam_op = apply_fn(total_grad, var, *args, **kwargs)
with tf.control_dependencies([adam_op]):
grad_acc_to_zero_op = grad_acc.assign(tf.zeros_like(grad_acc),
use_locking=self._use_locking)
return tf.group(adam_op, grad_acc_to_zero_op)
def accumulate_gradient(grad_acc, grad):
assign_op = tf.assign_add(grad_acc, grad, use_locking=self._use_locking)
return tf.group(assign_op) # Strip return value
return tf.cond(
tf.equal(self._get_iter_variable(), 0),
lambda: apply_adam(grad_acc, apply_fn, grad, var, *args, **kwargs),
lambda: accumulate_gradient(grad_acc, grad)) |
Updates beta_power variables every n batches and incrs counter. | def _finish(self, update_ops, name_scope):
"""Updates beta_power variables every n batches and incrs counter."""
iter_ = self._get_iter_variable()
beta1_power, beta2_power = self._get_beta_accumulators()
with tf.control_dependencies(update_ops):
with tf.colocate_with(iter_):
def update_beta_op():
update_beta1 = beta1_power.assign(
beta1_power * self._beta1_t,
use_locking=self._use_locking)
update_beta2 = beta2_power.assign(
beta2_power * self._beta2_t,
use_locking=self._use_locking)
return tf.group(update_beta1, update_beta2)
maybe_update_beta = tf.cond(
tf.equal(iter_, 0), update_beta_op, tf.no_op)
with tf.control_dependencies([maybe_update_beta]):
update_iter = iter_.assign(tf.mod(iter_ + 1, self._n_t),
use_locking=self._use_locking)
return tf.group(
*update_ops + [update_iter, maybe_update_beta], name=name_scope) |
A stack of transformer layers.
Args:
encoder_input: a Tensor
encoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
name: a string
Returns:
y: a Tensors | def transformer_revnet_encoder(encoder_input,
encoder_self_attention_bias,
hparams,
name="encoder"):
"""A stack of transformer layers.
Args:
encoder_input: a Tensor
encoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
name: a string
Returns:
y: a Tensors
"""
def f(x, side_input):
"""f(x) for reversible layer, self-attention layer."""
encoder_self_attention_bias = side_input[0]
old_hid_size = hparams.hidden_size
hparams.hidden_size = old_hid_size // 2
with tf.variable_scope("self_attention"):
y = common_attention.multihead_attention(
common_layers.layer_preprocess(
x, hparams), None, encoder_self_attention_bias,
hparams.attention_key_channels or hparams.hidden_size,
hparams.attention_value_channels or hparams.hidden_size,
hparams.hidden_size, hparams.num_heads, hparams.attention_dropout)
y = common_layers.layer_postprocess(x, y, hparams)
hparams.hidden_size = old_hid_size
return y
def g(x):
"""g(x) for reversible layer, feed-forward layer."""
old_hid_size = hparams.hidden_size
hparams.hidden_size = old_hid_size // 2
with tf.variable_scope("ffn"):
y = transformer.transformer_ffn_layer(
common_layers.layer_preprocess(x, hparams), hparams)
y = common_layers.layer_postprocess(x, y, hparams)
hparams.hidden_size = old_hid_size
return y
x1, x2 = tf.split(encoder_input, 2, axis=-1)
with tf.variable_scope(name):
y1, y2 = tf.contrib.layers.rev_block(
x1,
x2,
f,
g,
num_layers=hparams.num_hidden_layers,
f_side_input=[encoder_self_attention_bias],
is_training=hparams.mode == tf.estimator.ModeKeys.TRAIN)
y = tf.concat([y1, y2], axis=-1)
return common_layers.layer_preprocess(y, hparams) |
A stack of transformer layers.
Args:
decoder_input: a Tensor
encoder_output: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
name: a string
Returns:
y: a Tensors | def transformer_revnet_decoder(decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
name="decoder"):
"""A stack of transformer layers.
Args:
decoder_input: a Tensor
encoder_output: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
name: a string
Returns:
y: a Tensors
"""
def f(x, side_input):
"""f(x) for reversible layer, self-attention and enc-dec attention."""
decoder_self_attention_bias = side_input[0]
encoder_decoder_attention_bias = side_input[1]
encoder_output = side_input[2]
old_hid_size = hparams.hidden_size
hparams.hidden_size = old_hid_size // 2
with tf.variable_scope("self_attention"):
y = common_attention.multihead_attention(
common_layers.layer_preprocess(
x, hparams), None, decoder_self_attention_bias,
hparams.attention_key_channels or hparams.hidden_size,
hparams.attention_value_channels or hparams.hidden_size,
hparams.hidden_size, hparams.num_heads, hparams.attention_dropout)
y = common_layers.layer_postprocess(x, y, hparams)
if encoder_output is not None:
with tf.variable_scope("encdec_attention"):
y = common_attention.multihead_attention(
common_layers.layer_preprocess(
x, hparams), encoder_output, encoder_decoder_attention_bias,
hparams.attention_key_channels or hparams.hidden_size,
hparams.attention_value_channels or hparams.hidden_size,
hparams.hidden_size, hparams.num_heads, hparams.attention_dropout)
y = common_layers.layer_postprocess(x, y, hparams)
hparams.hidden_size = old_hid_size
return y
def g(x):
"""g(x) for reversible layer, feed-forward layer."""
old_hid_size = hparams.hidden_size
hparams.hidden_size = old_hid_size // 2
with tf.variable_scope("ffn"):
y = transformer.transformer_ffn_layer(
common_layers.layer_preprocess(x, hparams), hparams)
y = common_layers.layer_postprocess(x, y, hparams)
hparams.hidden_size = old_hid_size
return y
x1, x2 = tf.split(decoder_input, 2, axis=-1)
with tf.variable_scope(name):
y1, y2 = tf.contrib.layers.rev_block(
x1,
x2,
f,
g,
num_layers=hparams.num_hidden_layers,
f_side_input=[
decoder_self_attention_bias, encoder_decoder_attention_bias,
encoder_output
],
is_training=hparams.mode == tf.estimator.ModeKeys.TRAIN)
y = tf.concat([y1, y2], axis=-1)
return common_layers.layer_preprocess(y, hparams) |
Base hparams for TransformerRevnet. | def transformer_revnet_base():
"""Base hparams for TransformerRevnet."""
hparams = transformer.transformer_big()
# Use settings from transformer_n_da
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.learning_rate = 0.4
return hparams |
Base hparams for TransformerRevnet. | def transformer_revnet_big():
"""Base hparams for TransformerRevnet."""
hparams = transformer_revnet_base()
# The TransformerRevnet uses significantly less memory than the Transformer.
# Increase batch size and model size.
hparams.batch_size *= 2
hparams.hidden_size *= 2
hparams.num_heads *= 2
hparams.num_hidden_layers += 1
return hparams |
Over which devices do we split each training batch.
In old-fashioned async mode, we split the batch over all GPUs on the
current worker.
In sync mode, we split the batch over all the parameter server GPUs.
This function returns an expert_utils.Parallelism object, which can be used
to build the model. It is configured in a way that any variables created
by `tf.get_variable` will be assigned to the parameter servers and shared
between datashards.
Args:
daisy_chain_variables: whether to copy variables in a daisy chain on GPUs.
all_workers: whether the devices are all async workers or just this one.
Returns:
a expert_utils.Parallelism. | def data_parallelism_from_flags(daisy_chain_variables=True, all_workers=False):
"""Over which devices do we split each training batch.
In old-fashioned async mode, we split the batch over all GPUs on the
current worker.
In sync mode, we split the batch over all the parameter server GPUs.
This function returns an expert_utils.Parallelism object, which can be used
to build the model. It is configured in a way that any variables created
by `tf.get_variable` will be assigned to the parameter servers and shared
between datashards.
Args:
daisy_chain_variables: whether to copy variables in a daisy chain on GPUs.
all_workers: whether the devices are all async workers or just this one.
Returns:
a expert_utils.Parallelism.
"""
dp_arg_names = inspect.getargspec(data_parallelism).args
blacklist = ["daisy_chain_variables", "all_workers"]
kwargs = {}
for arg in dp_arg_names:
if arg in blacklist:
continue
kwargs[arg] = getattr(tf.flags.FLAGS, arg)
return data_parallelism(
daisy_chain_variables=daisy_chain_variables,
all_workers=all_workers,
**kwargs) |
See data_parallelism_from_flags. | def data_parallelism(daisy_chain_variables=True,
all_workers=False,
ps_replicas=0,
ps_job="/job:ps",
ps_gpu=0,
schedule="continuous_train_and_eval",
sync=False,
worker_gpu=1,
worker_replicas=1,
worker_id=0,
gpu_order="",
worker_job="/job:localhost",
no_data_parallelism=False):
"""See data_parallelism_from_flags."""
tf.logging.info("schedule=%s" % schedule)
tf.logging.info("worker_gpu=%s" % worker_gpu)
tf.logging.info("sync=%s" % sync)
def _ps_replicas(all_workers=False):
if all_workers:
return list(range(ps_replicas))
# Worker K will be using replicas {0,...n-1} + K*n if we have n replicas.
num_replicas = ps_replicas // worker_replicas
return [d + worker_id * num_replicas for d in range(num_replicas)]
def _gpu_order(num_gpus):
if gpu_order:
ret = [int(s) for s in gpu_order.split(" ")]
if len(ret) == num_gpus:
return ret
return list(range(num_gpus))
def _ps_gpus(all_workers=False):
ps_gpus = []
for d in _ps_replicas(all_workers=all_workers):
ps_gpus.extend([(d, gpu) for gpu in _gpu_order(ps_gpu)])
return ps_gpus
def ps_devices(all_workers=False):
"""List of ps devices (where to put the experts).
Args:
all_workers: whether the list is for all async workers or just this one.
Returns:
a list of device names
"""
if ps_replicas > 0:
if ps_gpu > 0:
return [
ps_job + "/task:%d/GPU:%d" % (d, gpu)
for (d, gpu) in _ps_gpus(all_workers=all_workers)
]
else:
return [
ps_job + "/task:%d" % d
for d in _ps_replicas(all_workers=all_workers)
]
else:
if worker_gpu > 0:
return ["gpu:%d" % d for d in _gpu_order(worker_gpu)]
else:
return [""]
def _replica_device_setter(worker_device):
if ps_replicas == 0:
return worker_device
return tf.train.replica_device_setter(
worker_device=worker_device,
ps_tasks=ps_replicas,
ps_device=ps_job + "/GPU:0" if ps_gpu > 0 else ps_job)
is_single_machine = ps_replicas == 0 and worker_replicas == 1
if no_data_parallelism:
datashard_devices = [""]
caching_devices = None
elif is_single_machine:
tf.logging.warn(
"Schedule=%s. Assuming that training is running on a single machine.",
schedule)
datashard_devices = ["gpu:%d" % d for d in _gpu_order(worker_gpu)]
if worker_gpu < 1:
datashard_devices += ["cpu:0"]
caching_devices = None
elif sync and ps_replicas > 0:
# compute on ps
datashard_devices = [
_replica_device_setter(d) for d in ps_devices(all_workers=all_workers)
]
if ps_gpu > 0 and ps_replicas > 1:
caching_devices = [
ps_job + "/task:%d/cpu:0" % d
for (d, _) in _ps_gpus(all_workers=all_workers)
]
else:
caching_devices = None
else:
# compute on worker - this is either a single-worker setup or asynchronous
# with parameter servers.
if worker_gpu > 1:
datashard_devices = [
_replica_device_setter(worker_job + "/GPU:%d" % d)
for d in _gpu_order(worker_gpu)
]
caching_devices = None
else:
datashard_devices = [_replica_device_setter(worker_job)]
caching_devices = None
tf.logging.info("datashard_devices: %s", datashard_devices)
tf.logging.info("caching_devices: %s", caching_devices)
tf.logging.info("ps_devices: %s", ps_devices(all_workers=all_workers))
return eu.Parallelism(
datashard_devices,
caching_devices=caching_devices,
daisy_chain_variables=daisy_chain_variables,
ps_devices=ps_devices(all_workers=all_workers)) |
Generate concatenated lines from file upto up_threshold characters. | def concat_generator(filename, up_threshold, low_threshold=10):
"""Generate concatenated lines from file upto up_threshold characters."""
txt = ""
for line in tf.gfile.Open(filename):
line = line.strip()
if len(txt) + len(line) + 1 >= up_threshold:
ret = txt
txt = ""
# We don't yield very short long parts to prevent noisy examples.
if len(ret) > low_threshold and len(ret) < up_threshold:
yield {"targets": ret}
if not txt:
txt = line
else:
txt = " ".join([txt, line]) |
Given python generators, generate from one, then from another, etc. | def mix_generators(generator_list):
"""Given python generators, generate from one, then from another, etc."""
i = 0
l = len(generator_list)
stopiters_seen = 0
while stopiters_seen <= l:
try:
yield six.next(generator_list[i % l])
i += 1
stopiters_seen = 0
except StopIteration:
i += 1
stopiters_seen += 1 |
Compute BLEU core summaries using the decoder output.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
A list of tf.Summary values if hook_args.hparams contains the
reference file and the translated file. | def compute_bleu_summaries(hook_args):
"""Compute BLEU core summaries using the decoder output.
Args:
hook_args: DecodeHookArgs namedtuple
Returns:
A list of tf.Summary values if hook_args.hparams contains the
reference file and the translated file.
"""
decode_hparams = hook_args.decode_hparams
if not (decode_hparams.decode_reference and decode_hparams.decode_to_file):
return None
values = []
bleu = 100 * bleu_hook.bleu_wrapper(
decode_hparams.decode_reference, decode_hparams.decode_to_file)
values.append(tf.Summary.Value(tag="BLEU", simple_value=bleu))
tf.logging.info("%s: BLEU = %6.2f" % (decode_hparams.decode_to_file, bleu))
if hook_args.hparams.mlperf_mode:
current_step = decode_hparams.mlperf_decode_step
mlperf_log.transformer_print(
key=mlperf_log.EVAL_TARGET, value=decode_hparams.mlperf_threshold)
mlperf_log.transformer_print(
key=mlperf_log.EVAL_ACCURACY,
value={
"epoch": max(current_step // decode_hparams.iterations_per_loop - 1,
0),
"value": bleu
})
mlperf_log.transformer_print(key=mlperf_log.EVAL_STOP)
if bleu >= decode_hparams.mlperf_threshold:
decode_hparams.set_hparam("mlperf_success", True)
return values |
Preprocessing to strip tags in SGM files. | def _preprocess_sgm(line, is_sgm):
"""Preprocessing to strip tags in SGM files."""
if not is_sgm:
return line
# In SGM files, remove <srcset ...>, <p>, <doc ...> lines.
if line.startswith("<srcset") or line.startswith("</srcset"):
return ""
if line.startswith("<doc") or line.startswith("</doc"):
return ""
if line.startswith("<p>") or line.startswith("</p>"):
return ""
# Strip <seg> tags.
line = line.strip()
if line.startswith("<seg") and line.endswith("</seg>"):
i = line.index(">")
return line[i + 1:-6] |
Concatenates all `datasets` and saves to `filename`. | def compile_data(tmp_dir, datasets, filename, datatypes_to_clean=None):
"""Concatenates all `datasets` and saves to `filename`."""
datatypes_to_clean = datatypes_to_clean or []
filename = os.path.join(tmp_dir, filename)
lang1_fname = filename + ".lang1"
lang2_fname = filename + ".lang2"
if tf.gfile.Exists(lang1_fname) and tf.gfile.Exists(lang2_fname):
tf.logging.info("Skipping compile data, found files:\n%s\n%s", lang1_fname,
lang2_fname)
return filename
with tf.gfile.GFile(lang1_fname, mode="w") as lang1_resfile:
with tf.gfile.GFile(lang2_fname, mode="w") as lang2_resfile:
for dataset in datasets:
url = dataset[0]
compressed_filename = os.path.basename(url)
compressed_filepath = os.path.join(tmp_dir, compressed_filename)
if url.startswith("http"):
generator_utils.maybe_download(tmp_dir, compressed_filename, url)
if dataset[1][0] == "tmx":
cleaning_requested = "tmx" in datatypes_to_clean
tmx_filename = os.path.join(tmp_dir, dataset[1][1])
if tmx_filename.endswith(".gz"):
with gzip.open(tmx_filename, "rb") as tmx_file:
_tmx_to_source_target(tmx_file, lang1_resfile, lang2_resfile,
do_cleaning=cleaning_requested)
else:
with tf.gfile.Open(tmx_filename) as tmx_file:
_tmx_to_source_target(tmx_file, lang1_resfile, lang2_resfile,
do_cleaning=cleaning_requested)
elif dataset[1][0] == "tsv":
_, src_column, trg_column, glob_pattern = dataset[1]
filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern))
if not filenames:
# Capture *.tgz and *.tar.gz too.
mode = "r:gz" if compressed_filepath.endswith("gz") else "r"
with tarfile.open(compressed_filepath, mode) as corpus_tar:
corpus_tar.extractall(tmp_dir)
filenames = tf.gfile.Glob(os.path.join(tmp_dir, glob_pattern))
for tsv_filename in filenames:
if tsv_filename.endswith(".gz"):
new_filename = tsv_filename.strip(".gz")
generator_utils.gunzip_file(tsv_filename, new_filename)
tsv_filename = new_filename
with tf.gfile.Open(tsv_filename) as tsv_file:
for line in tsv_file:
if line and "\t" in line:
parts = line.split("\t")
source, target = parts[src_column], parts[trg_column]
source, target = source.strip(), target.strip()
clean_pairs = [(source, target)]
if "tsv" in datatypes_to_clean:
clean_pairs = cleaner_en_xx.clean_en_xx_pairs(clean_pairs)
for source, target in clean_pairs:
if source and target:
lang1_resfile.write(source)
lang1_resfile.write("\n")
lang2_resfile.write(target)
lang2_resfile.write("\n")
else:
lang1_filename, lang2_filename = dataset[1]
lang1_filepath = os.path.join(tmp_dir, lang1_filename)
lang2_filepath = os.path.join(tmp_dir, lang2_filename)
is_sgm = (
lang1_filename.endswith("sgm") and lang2_filename.endswith("sgm"))
if not (tf.gfile.Exists(lang1_filepath) and
tf.gfile.Exists(lang2_filepath)):
# For .tar.gz and .tgz files, we read compressed.
mode = "r:gz" if compressed_filepath.endswith("gz") else "r"
with tarfile.open(compressed_filepath, mode) as corpus_tar:
corpus_tar.extractall(tmp_dir)
if lang1_filepath.endswith(".gz"):
new_filepath = lang1_filepath.strip(".gz")
generator_utils.gunzip_file(lang1_filepath, new_filepath)
lang1_filepath = new_filepath
if lang2_filepath.endswith(".gz"):
new_filepath = lang2_filepath.strip(".gz")
generator_utils.gunzip_file(lang2_filepath, new_filepath)
lang2_filepath = new_filepath
for example in text_problems.text2text_txt_iterator(
lang1_filepath, lang2_filepath):
line1res = _preprocess_sgm(example["inputs"], is_sgm)
line2res = _preprocess_sgm(example["targets"], is_sgm)
clean_pairs = [(line1res, line2res)]
if "txt" in datatypes_to_clean:
clean_pairs = cleaner_en_xx.clean_en_xx_pairs(clean_pairs)
for line1res, line2res in clean_pairs:
if line1res and line2res:
lang1_resfile.write(line1res)
lang1_resfile.write("\n")
lang2_resfile.write(line2res)
lang2_resfile.write("\n")
return filename |
Get vocab for distill problems. | def get_or_create_vocab(self, data_dir, tmp_dir, force_get=False):
"""Get vocab for distill problems."""
# We assume that vocab file is present in data_dir directory where the
# data generated will be stored.
vocab_filepath = os.path.join(data_dir, self.vocab_filename)
encoder = text_encoder.SubwordTextEncoder(vocab_filepath)
return encoder |
Set hparams overrides from unparsed args list. | def set_hparams_from_args(args):
"""Set hparams overrides from unparsed args list."""
if not args:
return
hp_prefix = "--hp_"
tf.logging.info("Found unparsed command-line arguments. Checking if any "
"start with %s and interpreting those as hparams "
"settings.", hp_prefix)
pairs = []
i = 0
while i < len(args):
arg = args[i]
if arg.startswith(hp_prefix):
pairs.append((arg[len(hp_prefix):], args[i+1]))
i += 2
else:
tf.logging.warn("Found unknown flag: %s", arg)
i += 1
as_hparams = ",".join(["%s=%s" % (key, val) for key, val in pairs])
if FLAGS.hparams:
as_hparams = "," + as_hparams
FLAGS.hparams += as_hparams |
Create hparams. | def create_hparams():
"""Create hparams."""
if FLAGS.use_tpu and "tpu" not in FLAGS.hparams_set:
tf.logging.warn("Not all hyperparameter sets work on TPU. "
"Prefer hparams_sets with a '_tpu' suffix, "
"e.g. transformer_tpu, if available for your model.")
hparams_path = os.path.join(FLAGS.output_dir, "hparams.json")
return trainer_lib.create_hparams(FLAGS.hparams_set, FLAGS.hparams,
hparams_path=hparams_path) |
Create a run config.
Args:
hp: model hyperparameters
output_dir: model's output directory, defaults to output_dir flag.
Returns:
a run config | def create_run_config(hp, output_dir=None):
"""Create a run config.
Args:
hp: model hyperparameters
output_dir: model's output directory, defaults to output_dir flag.
Returns:
a run config
"""
save_ckpt_steps = max(FLAGS.iterations_per_loop, FLAGS.local_eval_frequency)
save_ckpt_secs = FLAGS.save_checkpoints_secs or None
if save_ckpt_secs:
save_ckpt_steps = None
assert FLAGS.output_dir or FLAGS.checkpoint_path
tpu_config_extra_kwargs = {}
if FLAGS.tpu_job_name is not None:
tpu_config_extra_kwargs["tpu_job_name"] = FLAGS.tpu_job_name
if getattr(hp, "mtf_mode", False):
save_ckpt_steps = None # Disable the default saver
save_ckpt_secs = None # Disable the default saver
tpu_config_extra_kwargs = {
"num_cores_per_replica": 1,
"per_host_input_for_training": tpu_config.InputPipelineConfig.BROADCAST,
}
# the various custom getters we have written do not play well together yet.
# TODO(noam): ask rsepassi for help here.
daisy_chain_variables = (
hp.daisy_chain_variables and
hp.activation_dtype == "float32" and
hp.weight_dtype == "float32")
return trainer_lib.create_run_config(
model_name=FLAGS.model,
model_dir=output_dir or os.path.expanduser(FLAGS.output_dir),
master=FLAGS.master,
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.tpu_num_shards,
log_device_placement=FLAGS.log_device_placement,
save_checkpoints_steps=save_ckpt_steps,
save_checkpoints_secs=save_ckpt_secs,
keep_checkpoint_max=FLAGS.keep_checkpoint_max,
keep_checkpoint_every_n_hours=FLAGS.keep_checkpoint_every_n_hours,
num_gpus=FLAGS.worker_gpu,
gpu_order=FLAGS.gpu_order,
num_async_replicas=FLAGS.worker_replicas,
gpu_mem_fraction=FLAGS.worker_gpu_memory_fraction,
enable_graph_rewriter=FLAGS.enable_graph_rewriter,
use_tpu=FLAGS.use_tpu,
use_tpu_estimator=FLAGS.use_tpu_estimator,
xla_jit_level=FLAGS.xla_jit_level,
schedule=FLAGS.schedule,
no_data_parallelism=hp.no_data_parallelism,
optionally_use_dist_strat=FLAGS.optionally_use_dist_strat,
daisy_chain_variables=daisy_chain_variables,
ps_replicas=FLAGS.ps_replicas,
ps_job=FLAGS.ps_job,
ps_gpu=FLAGS.ps_gpu,
sync=FLAGS.sync,
worker_id=FLAGS.worker_id,
worker_job=FLAGS.worker_job,
random_seed=FLAGS.random_seed,
tpu_infeed_sleep_secs=FLAGS.tpu_infeed_sleep_secs,
inter_op_parallelism_threads=FLAGS.inter_op_parallelism_threads,
log_step_count_steps=FLAGS.log_step_count_steps,
intra_op_parallelism_threads=FLAGS.intra_op_parallelism_threads,
tpu_config_extra_kwargs=tpu_config_extra_kwargs,
cloud_tpu_name=FLAGS.cloud_tpu_name) |
Saves FLAGS and hparams to output_dir. | def save_metadata(hparams):
"""Saves FLAGS and hparams to output_dir."""
output_dir = os.path.expanduser(FLAGS.output_dir)
if not tf.gfile.Exists(output_dir):
tf.gfile.MakeDirs(output_dir)
# Save FLAGS in txt file
if hasattr(FLAGS, "flags_into_string"):
flags_str = FLAGS.flags_into_string()
t2t_flags_str = "\n".join([
"--%s=%s" % (f.name, f.value)
for f in FLAGS.flags_by_module_dict()["tensor2tensor.utils.flags"]
])
else:
flags_dict = FLAGS.__dict__["__flags"]
flags_str = "\n".join(
["--%s=%s" % (name, str(f)) for (name, f) in flags_dict.items()])
t2t_flags_str = None
flags_txt = os.path.join(output_dir, "flags.txt")
with tf.gfile.Open(flags_txt, "w") as f:
f.write(flags_str)
if t2t_flags_str:
t2t_flags_txt = os.path.join(output_dir, "flags_t2t.txt")
with tf.gfile.Open(t2t_flags_txt, "w") as f:
f.write(t2t_flags_str)
# Save hparams as hparams.json
new_hparams = hparams_lib.copy_hparams(hparams)
# Modality class is not JSON serializable so remove.
new_hparams.del_hparam("modality")
hparams_fname = os.path.join(output_dir, "hparams.json")
with tf.gfile.Open(hparams_fname, "w") as f:
f.write(new_hparams.to_json(indent=0, sort_keys=True)) |
A stack of convolution blocks with residual connection. | def residual_block(x, hparams):
"""A stack of convolution blocks with residual connection."""
k = (hparams.kernel_height, hparams.kernel_width)
dilations_and_kernels = [((1, 1), k) for _ in range(3)]
y = common_layers.subseparable_conv_block(
x,
hparams.hidden_size,
dilations_and_kernels,
padding="SAME",
separability=0,
name="residual_block")
x = common_layers.layer_norm(x + y, hparams.hidden_size, name="lnorm")
return tf.nn.dropout(x, 1.0 - hparams.dropout) |
Xception body. | def xception_internal(inputs, hparams):
"""Xception body."""
with tf.variable_scope("xception"):
cur = inputs
if cur.get_shape().as_list()[1] > 200:
# Large image, Xception entry flow
cur = xception_entry(cur, hparams.hidden_size)
else:
# Small image, conv
cur = common_layers.conv_block(
cur,
hparams.hidden_size, [((1, 1), (3, 3))],
first_relu=False,
padding="SAME",
force2d=True,
name="small_image_conv")
for i in range(hparams.num_hidden_layers):
with tf.variable_scope("layer_%d" % i):
cur = residual_block(cur, hparams)
return xception_exit(cur) |
Xception entry flow. | def xception_entry(inputs, hidden_dim):
"""Xception entry flow."""
with tf.variable_scope("xception_entry"):
def xnet_resblock(x, filters, res_relu, name):
"""Resblock."""
with tf.variable_scope(name):
y = common_layers.separable_conv_block(
x,
filters, [((1, 1), (3, 3)), ((1, 1), (3, 3))],
first_relu=True,
padding="SAME",
force2d=True,
name="sep_conv_block")
y = common_layers.pool(y, (3, 3), "MAX", "SAME", strides=(2, 2))
return y + common_layers.conv_block(
x,
filters, [((1, 1), (1, 1))],
padding="SAME",
strides=(2, 2),
first_relu=res_relu,
force2d=True,
name="res_conv0")
tf.summary.image("inputs", inputs, max_outputs=2)
x = common_layers.conv_block(
inputs,
32, [((1, 1), (3, 3))],
first_relu=False,
padding="SAME",
strides=(2, 2),
force2d=True,
name="conv0")
x = common_layers.conv_block(
x, 64, [((1, 1), (3, 3))], padding="SAME", force2d=True, name="conv1")
x = xnet_resblock(x, min(128, hidden_dim), True, "block0")
x = xnet_resblock(x, min(256, hidden_dim), False, "block1")
return xnet_resblock(x, hidden_dim, False, "block2") |
Xception exit flow. | def xception_exit(inputs):
"""Xception exit flow."""
with tf.variable_scope("xception_exit"):
x = inputs
x_shape = x.get_shape().as_list()
if x_shape[1] is None or x_shape[2] is None:
length_float = tf.to_float(tf.shape(x)[1])
length_float *= tf.to_float(tf.shape(x)[2])
spatial_dim_float = tf.sqrt(length_float)
spatial_dim = tf.to_int32(spatial_dim_float)
x_depth = x_shape[3]
x = tf.reshape(x, [-1, spatial_dim, spatial_dim, x_depth])
elif x_shape[1] != x_shape[2]:
spatial_dim = int(math.sqrt(float(x_shape[1] * x_shape[2])))
if spatial_dim * spatial_dim != x_shape[1] * x_shape[2]:
raise ValueError("Assumed inputs were square-able but they were "
"not. Shape: %s" % x_shape)
x = tf.reshape(x, [-1, spatial_dim, spatial_dim, x_depth])
x = common_layers.conv_block_downsample(x, (3, 3), (2, 2), "SAME")
return tf.nn.relu(x) |
Returns a plaintext representation of HTML content. | def get_text_from_html(html):
"""Returns a plaintext representation of HTML content."""
try:
soup = bs4.BeautifulSoup(html, "html.parser")
except: # pylint: disable=bare-except
# Some docs don't parse
return ""
# Remove script and style tags
for s in soup(["script", "style"]):
s.decompose()
return "\n".join([s for s in _soup_strings(soup)]) |
Return text strings in soup. | def _soup_strings(soup):
"""Return text strings in soup."""
paragraph_tags = set([
"caption", "details", "h1", "h2", "h3", "h4", "h5", "h6", "li", "p", "td",
"div", "span"
])
skip_children = None
for descendant in soup.descendants:
# If we've treated a tag as a contiguous paragraph, don't re-emit the
# children (see below).
if skip_children is not None:
try:
in_skip = descendant in skip_children # pylint: disable=unsupported-membership-test
except RecursionError: # pylint: disable=undefined-variable
# Possible for this check to hit a nasty infinite recursion because of
# BeautifulSoup __eq__ checks.
in_skip = True
if in_skip:
continue
else:
skip_children = None
# Treat some tags as contiguous paragraphs, regardless of other tags nested
# inside (like <a> or <b>).
if isinstance(descendant, bs4.Tag):
if descendant.name in paragraph_tags:
if descendant.find_all(paragraph_tags):
# If there are nested paragraph tags, don't treat it as a single
# contiguous tag.
continue
skip_children = list(descendant.descendants)
text = " ".join(descendant.get_text(" ", strip=True).split())
if text:
yield text
continue
if (isinstance(descendant, bs4.Comment) or
not isinstance(descendant, bs4.NavigableString)):
continue
text = " ".join(descendant.strip().split())
if text:
yield text |
Set of hyperparameters. | def image_transformer_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.hidden_size = 512
hparams.batch_size = 4
hparams.max_length = 3075
hparams.dropout = 0.0
hparams.clip_grad_norm = 0. # i.e. no gradient clipping
hparams.optimizer_adam_epsilon = 1e-9
hparams.learning_rate_decay_scheme = "noam"
hparams.learning_rate = 0.1
hparams.learning_rate_warmup_steps = 4000
hparams.initializer_gain = 0.2
hparams.num_hidden_layers = 6
hparams.initializer = "uniform_unit_scaling"
hparams.weight_decay = 0.0
hparams.optimizer_adam_beta1 = 0.9
hparams.optimizer_adam_beta2 = 0.98
hparams.label_smoothing = 0.0
hparams.bottom["targets"] = modalities.image_channel_embeddings_bottom
hparams.top["targets"] = modalities.identity_top
hparams.norm_type = "layer"
hparams.layer_prepostprocess_dropout = 0.0
hparams.add_hparam("filter_size", 512) # Add new ones like this.
# attention-related flags
hparams.add_hparam("num_heads", 8)
hparams.add_hparam("attention_key_channels", 0)
hparams.add_hparam("attention_value_channels", 0)
hparams.add_hparam("ffn_layer", "conv_hidden_relu")
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
hparams.add_hparam("attention_dropout", 0.0)
hparams.add_hparam("relu_dropout", 0.0)
hparams.add_hparam("pos", "timing") # timing, none
hparams.add_hparam("nbr_decoder_problems", 1)
hparams.add_hparam("num_output_layers", 3)
hparams.add_hparam("block_size", 1)
# dilated attention based flags
hparams.add_hparam("gap_sizes", [2, 4, 8, 16, 32, 64, 2, 4, 8, 16, 32, 64])
# image size related flags
# assuming that the image has same height and width
hparams.add_hparam("img_len", 32)
hparams.add_hparam("num_channels", 3)
# Local attention params
hparams.add_hparam("local_and_global_att", False)
hparams.add_hparam("block_length", 256)
hparams.add_hparam("block_width", 128)
hparams.add_hparam("num_encoder_layers", 4)
hparams.add_hparam("num_decoder_layers", 12)
hparams.add_hparam("dec_attention_type", cia.AttentionType.LOCAL_1D)
hparams.add_hparam("block_raster_scan", False)
# multipos attention params
hparams.add_hparam("q_filter_width", 1)
hparams.add_hparam("kv_filter_width", 1)
hparams.add_hparam("likelihood", cia.DistributionType.CAT)
hparams.add_hparam("unconditional", False) # unconditional generation
# parameters of discretized mixture of logistics loss from pixel cnn++
hparams.add_hparam("num_mixtures", 10)
# These parameters are only used when ffn_layer=="local_moe_tpu"
hparams.add_hparam("moe_overhead_train", 1.0)
hparams.add_hparam("moe_overhead_eval", 2.0)
hparams.moe_num_experts = 8
hparams.moe_loss_coef = 1e-3
# These parameters are for relative attention
hparams.add_hparam("shared_rel", False) # share relative embeddings
return hparams |
Best config for 2.90 bits/dim on CIFAR10 using cross entropy. | def imagetransformer_cifar10_base():
"""Best config for 2.90 bits/dim on CIFAR10 using cross entropy."""
hparams = image_transformer_base()
hparams.batch_size = 4
hparams.num_heads = 4
hparams.num_decoder_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.learning_rate = 0.5
hparams.learning_rate_warmup_steps = 4000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.3
hparams.unconditional = True
return hparams |
Best config for 2.90 bits/dim on CIFAR10 using DMOL. | def imagetransformer_cifar10_base_dmol():
"""Best config for 2.90 bits/dim on CIFAR10 using DMOL."""
hparams = image_transformer_base()
hparams.likelihood = cia.DistributionType.DMOL
hparams.num_channels = 1
hparams.bottom["targets"] = modalities.image_channel_compress_targets_bottom
hparams.top["targets"] = modalities.identity_top
hparams.num_heads = 8
hparams.batch_size = 8
hparams.sampling_method = "random"
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.summarize_grads = True
hparams.hidden_size = 256
hparams.filter_size = 512
hparams.attention_key_channels = 512
hparams.attention_value_channels = 512
hparams.num_decoder_layers = 12
hparams.layer_prepostprocess_dropout = 0.1
hparams.learning_rate = 0.1
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.pos = "emb"
hparams.unconditional = True
return hparams |
Transformer base params for cifar-10. | def imagetransformer_base_tpu():
"""Transformer base params for cifar-10."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 12
hparams.block_length = 128
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 6000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.3
return hparams |
Transformer base params for cifar-10. | def imagetransformer_base_imagenet_tpu():
"""Transformer base params for cifar-10."""
hparams = imagetransformer_base_tpu()
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 12
hparams.block_length = 128
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.1
return hparams |
separate rgb embeddings. | def imagetransformer_sep_channels():
"""separate rgb embeddings."""
hparams = imagetransformer_base()
hparams.num_heads = 4
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 256
hparams.filter_size = 512
hparams.num_hidden_layers = 6
return hparams |
separate rgb embeddings. | def imagetransformer_sep_channels_8l():
"""separate rgb embeddings."""
hparams = imagetransformer_base()
hparams.num_heads = 4
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 256
hparams.filter_size = 256
hparams.num_hidden_layers = 8
hparams.sampling_method = "random"
return hparams |
big 1d model for conditional image generation.2.99 on cifar10. | def imagetransformer_base_8l_8h_big_cond_dr03_dan():
"""big 1d model for conditional image generation.2.99 on cifar10."""
hparams = imagetransformer_sep_channels_8l()
hparams.block_width = 256
hparams.block_length = 256
hparams.hidden_size = 512
hparams.num_heads = 8
hparams.filter_size = 2048
hparams.batch_size = 4
hparams.max_length = 3075
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.num_decoder_layers = 8
hparams.layer_prepostprocess_dropout = 0.3
return hparams |
big 1d model for unconditional generation on imagenet. | def imagetransformer_base_10l_8h_big_uncond_dr03_dan_64():
"""big 1d model for unconditional generation on imagenet."""
hparams = imagetransformer_base_10l_8h_big_cond_dr03_dan()
hparams.unconditional = True
hparams.max_length = 14000
hparams.batch_size = 1
hparams.img_len = 64
hparams.layer_prepostprocess_dropout = 0.1
return hparams |
separate rgb embeddings. | def imagetransformerpp_sep_channels_8l_8h():
"""separate rgb embeddings."""
hparams = imagetransformer_base()
hparams.likelihood = cia.DistributionType.DMOL
hparams.num_channels = 1
hparams.bottom["targets"] = modalities.image_channel_compress_targets_bottom
hparams.top["targets"] = modalities.identity_top
hparams.num_heads = 8
hparams.batch_size = 4
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 512
hparams.filter_size = 512
hparams.num_hidden_layers = 8
hparams.sampling_method = "random"
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
hparams.summarize_grads = True
hparams.learning_rate = 0.1
return hparams |
big 1d model for conditional image generation.2.99 on cifar10. | def imagetransformerpp_base_8l_8h_big_cond_dr03_dan():
"""big 1d model for conditional image generation.2.99 on cifar10."""
hparams = imagetransformerpp_sep_channels_8l_8h()
hparams.hidden_size = 512
hparams.num_heads = 8
hparams.filter_size = 2048
hparams.batch_size = 4
hparams.max_length = 3075
hparams.layer_prepostprocess_dropout = 0.3
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.summarize_grads = True
hparams.learning_rate = 0.01
return hparams |
Gets to 2.92 in just under 4 days on 8 p100s. | def imagetransformerpp_base_14l_8h_big_uncond_dr03_dan_p():
"""Gets to 2.92 in just under 4 days on 8 p100s."""
hparams = imagetransformerpp_base_12l_8h_big_uncond_dr03_dan_l()
hparams.num_decoder_layers = 14
hparams.batch_size = 8
hparams.layer_prepostprocess_dropout = 0.2
return hparams |
For 256x256. | def imagetransformerpp_base_5l_8h_big_uncond_dr00_dan_g_bs1():
"""For 256x256."""
hparams = imagetransformerpp_base_10l_8h_big_uncond_dr03_dan_g()
# TODO(trandustin): I forgot to set this in the runs! Maybe it's not used in
# image transformer training implementation?
# hparams.img_len = 256
hparams.max_length = 66000 # allow for 256x256
hparams.batch_size = 1
hparams.num_decoder_layers = 5
hparams.hidden_size = 128
hparams.filter_size = 128
hparams.attention_key_channels = 64
hparams.attention_value_channels = 64
hparams.layer_prepostprocess_dropout = 0.0
return hparams |
Dilated hparams. | def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated():
"""Dilated hparams."""
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan()
hparams.gap_sizes = [0, 16, 64, 0, 16, 64, 128, 0]
hparams.dec_attention_type = cia.AttentionType.DILATED
hparams.block_length = 128
hparams.block_width = 128
hparams.add_hparam("num_memory_blocks", 1)
return hparams |
big 1d model for conditional image generation. | def imagetransformer_base_12l_8h_big():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_sep_channels_8l_8h()
hparams.filter_size = 1024
hparams.num_decoder_layers = 12
hparams.batch_size = 1
hparams.hidden_size = 512
hparams.learning_rate_warmup_steps = 4000
hparams.sampling_method = "random"
hparams.beam_size = 1
hparams.block_width = 256
return hparams |
hparams fo 12 layer big 1d model for imagenet 64x64. | def imagetransformer1d_base_8l_64by64():
"""hparams fo 12 layer big 1d model for imagenet 64x64."""
hparams = image_transformer_base()
hparams.num_heads = 8
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.num_decoder_layers = 8
hparams.batch_size = 1
hparams.block_length = 512
hparams.block_width = 768
hparams.layer_prepostprocess_dropout = 0.1
hparams.max_length = 14000
hparams.unconditional = int(False)
return hparams |
separate rgb embeddings. | def imagetransformer_sep_channels_12l_16h_imagenet_large():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_8l_8h()
hparams.num_hidden_layers = 12
hparams.batch_size = 1
hparams.filter_size = 2048
hparams.num_heads = 16
hparams.learning_rate_warmup_steps = 16000
hparams.sampling_method = "random"
hparams.learning_rate = 0.1
return hparams |
separate rgb embeddings. | def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 256
return hparams |
separate rgb embeddings. | def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc_128():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 128
return hparams |
big 1d model for conditional image generation. | def imagetransformer_base_10l_16h_big_uncond_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.layer_prepostprocess_dropout = 0.1
return hparams |
big 1d model for conditional image generation. | def imagetransformer_base_10l_16h_big_dr01_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 16
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.unconditional = False
hparams.layer_prepostprocess_dropout = 0.1
return hparams |
separate rgb embeddings. | def imagetransformer_sep_channels_8l_8h():
"""separate rgb embeddings."""
hparams = imagetransformer_base()
hparams.num_heads = 8
hparams.batch_size = 1
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 512
hparams.filter_size = 512
hparams.num_hidden_layers = 8
hparams.sampling_method = "random"
return hparams |
big 1d model for conditional image generation. | def imagetransformer_bas8l_8h_big_uncond_dr03_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_14l_8h_big_dr01()
# num_hidden_layers
hparams.num_decoder_layers = 8
hparams.num_heads = 8
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.layer_prepostprocess_dropout = 0.3
return hparams |
separate rgb embeddings. | def imagetransformer_sep_channels_8l_8h_local_and_global_att():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_8l_8h()
hparams.num_heads = 8
hparams.batch_size = 1
hparams.attention_key_channels = hparams.attention_value_channels = 0
hparams.hidden_size = 256
hparams.filter_size = 256
hparams.num_hidden_layers = 4
hparams.sampling_method = "random"
hparams.local_and_global_att = True
return hparams |
big 1d model for conditional image generation. | def imagetransformer_base_10l_16h_big_dr01_moe_imgnet():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_base_10l_16h_big_dr01_imgnet()
hparams.initializer = "orthogonal"
hparams.learning_rate_warmup_steps = 16000
hparams.add_hparam("moe_layers_decoder", "2,7") # Which layer is MoE.
hparams.moe_hidden_sizes = "4096" # Hidden layer sizes (comma-separated).
hparams.moe_num_experts = 64 # Number of experts in each MoE layer.
hparams.moe_k = 4 # How many experts to use per batch element (try 2 or 4).
hparams.moe_loss_coef = 3e-2 # MoE loss coefficient (1e-2 is usually ok).
hparams.scheduled_sampling_prob = 0.1
hparams.scheduled_sampling_warmup_steps = 200000
return hparams |
Set of hyperparameters for a very small imagetransformer with MoE. | def imagetransformer_moe_tiny():
"""Set of hyperparameters for a very small imagetransformer with MoE."""
hparams = imagetransformer_tiny()
hparams.hidden_size = 64
hparams.batch_size = 1
hparams.num_hidden_layers = 3
hparams.dec_attention_type = cia.AttentionType.MOE_LOCAL_1D
hparams.add_hparam("moe_layers_decoder", "1") # Which layer is MoE.
hparams.moe_hidden_sizes = "1024" # Hidden layer sizes (comma-separated).
hparams.moe_num_experts = 16 # Number of experts in each MoE layer.
hparams.moe_k = 2 # How many experts to use per batch element (try 2 or 4).
hparams.moe_loss_coef = 1e-2 # MoE loss coefficient (1e-2 is usually ok).
return hparams |
Hparams for training imagetransformer on tpu. | def imagetransformer_sep_channels_8l_tpu():
"""Hparams for training imagetransformer on tpu."""
hparams = imagetransformer_sep_channels_8l()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.shared_embedding_and_softmax_weights = False
return hparams |
Small model for tpu cifar 10. | def imagetransformer_b10l_4h_big_uncond_dr03_tpu():
"""Small model for tpu cifar 10."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 10
hparams.block_length = 128
hparams.hidden_size = 512
hparams.filter_size = 1024
hparams.learning_rate = 0.2
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
return hparams |
Moe tpu params. | def imagetransformer_b10l_dr03_moe_tpu():
"""Moe tpu params."""
hparams = imagetransformer_b10l_4h_big_uncond_dr03_tpu()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 10
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.ffn_layer = "local_moe_tpu"
return hparams |
TPU related small model. | def imagetransformer_b10l_4h_big_uncond_dr03_lr025_tpu():
"""TPU related small model."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 10
hparams.learning_rate = 0.25
hparams.learning_rate_warmup_steps = 8000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
# hparams.unconditional = True
return hparams |
works very well on 4x4. | def imagetransformer_b12l_4h_b256_uncond_dr03_tpu():
"""works very well on 4x4."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.learning_rate = 0.5
hparams.learning_rate_warmup_steps = 4000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.3
hparams.unconditional = True
return hparams |
works very well on 4x4. | def imagetransformer_b12l_4h_b256_uncond_dr03_rel_tpu():
"""works very well on 4x4."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
hparams.shared_rel = True
hparams.dec_attention_type = cia.AttentionType.RELATIVE_LOCAL_1D
return hparams |
Range of hyperparameters for vizier. | def imagetransformer_cifar_tpu_range(rhp):
"""Range of hyperparameters for vizier."""
# After starting from base, set intervals for some parameters.
rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE)
rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16])
rhp.set_discrete("hidden_size", [256, 512, 1024])
rhp.set_discrete("block_length", [128, 256, 512])
rhp.set_categorical("dec_attention_type", [
cia.AttentionType.RELATIVE_LOCAL_1D, cia.AttentionType.LOCAL_1D]) |
TPU related imagenet model. | def imagetransformer_b12l_4h_b128_h512_uncond_dr01_im():
"""TPU related imagenet model."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_warmup_steps = 6000
hparams.layer_prepostprocess_dropout = 0.1
return hparams |
TPU related small model. | def imagetransformer_b12l_4h_uncond_dr03_tpu():
"""TPU related small model."""
hparams = imagetransformer_b12l_4h_b256_uncond_dr03_tpu()
hparams.learning_rate = 0.2
hparams.learning_rate_warmup_steps = 4000
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.3
return hparams |
TPU config for cifar 10. | def imagetransformer_b12l_4h_b128_uncond_dr03_tpu():
"""TPU config for cifar 10."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 2
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 12
hparams.block_length = 128
hparams.hidden_size = 256
hparams.filter_size = 2048
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.1
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_warmup_steps = 10000
return hparams |
TPU related 12 layer 8 heads model. | def imagetransformer_b12l_8h_b256_uncond_dr03_tpu():
"""TPU related 12 layer 8 heads model."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 2
hparams.num_heads = 8 # heads are expensive on tpu
hparams.num_decoder_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.filter_size = 2048
hparams.layer_preprocess_sequence = "none"
hparams.layer_postprocess_sequence = "dan"
hparams.layer_prepostprocess_dropout = 0.3
return hparams |
big 1d model for conditional image generation. | def imagetransformer_b10l_4h_big_uncond_dr01_tpu():
"""big 1d model for conditional image generation."""
hparams = imagetransformer_b12l_4h_big_uncond_dr03_tpu()
# num_hidden_layers
hparams.num_decoder_layers = 10
hparams.num_heads = 4
hparams.hidden_size = 1024
hparams.filter_size = 4096
hparams.batch_size = 1
hparams.layer_prepostprocess_dropout = 0.1
return hparams |
Context manager wrapping the training loop, updates step counters. | def training_loop(self):
"""Context manager wrapping the training loop, updates step counters."""
if not self.restarting:
self._write_counters(self._local_step_at_start, self._global_step)
tf.logging.info(
"Training %s up to %d, %d to go", self.model_mode,
self.target_local_step, self.steps_to_go
)
yield
self._write_counters(self.target_local_step, -1) |
Reads words from a file. | def _read_words(filename):
"""Reads words from a file."""
with tf.gfile.GFile(filename, "r") as f:
if sys.version_info[0] >= 3:
return f.read().replace("\n", " %s " % EOS).split()
else:
return f.read().decode("utf-8").replace("\n", " %s " % EOS).split() |
Reads a file to build a vocabulary of `vocab_size` most common words.
The vocabulary is sorted by occurrence count and has one word per line.
Originally from:
https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py
Args:
filename: file to read list of words from.
vocab_path: path where to save the vocabulary.
vocab_size: size of the vocabulary to generate. | def _build_vocab(filename, vocab_path, vocab_size):
"""Reads a file to build a vocabulary of `vocab_size` most common words.
The vocabulary is sorted by occurrence count and has one word per line.
Originally from:
https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py
Args:
filename: file to read list of words from.
vocab_path: path where to save the vocabulary.
vocab_size: size of the vocabulary to generate.
"""
data = _read_words(filename)
counter = collections.Counter(data)
count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
words, _ = list(zip(*count_pairs))
words = words[:vocab_size]
with open(vocab_path, "w") as f:
f.write("\n".join(words)) |
Reads from file and returns a `TokenTextEncoder` for the vocabulary. | def _get_token_encoder(vocab_dir, vocab_name, filename):
"""Reads from file and returns a `TokenTextEncoder` for the vocabulary."""
vocab_path = os.path.join(vocab_dir, vocab_name)
if not tf.gfile.Exists(vocab_path):
_build_vocab(filename, vocab_path, 10000)
return text_encoder.TokenTextEncoder(vocab_path) |
Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
vocab_type: which vocabulary are we using.
Returns:
The list of names of files. | def _maybe_download_corpus(tmp_dir, vocab_type):
"""Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
vocab_type: which vocabulary are we using.
Returns:
The list of names of files.
"""
filename = os.path.basename(PTB_URL)
compressed_filepath = generator_utils.maybe_download(
tmp_dir, filename, PTB_URL)
ptb_files = []
ptb_char_files = []
with tarfile.open(compressed_filepath, "r:gz") as tgz:
files = []
# Selecting only relevant files.
for m in tgz.getmembers():
if "ptb" in m.name and ".txt" in m.name:
if "char" in m.name:
ptb_char_files += [m.name]
else:
ptb_files += [m.name]
files += [m]
tgz.extractall(tmp_dir, members=files)
if vocab_type == text_problems.VocabType.CHARACTER:
return ptb_char_files
else:
return ptb_files |
Normalize attention matrices and reshape as necessary. | def resize(att_mat, max_length=None):
"""Normalize attention matrices and reshape as necessary."""
for i, att in enumerate(att_mat):
# Add extra batch dim for viz code to work.
if att.ndim == 3:
att = np.expand_dims(att, axis=0)
if max_length is not None:
# Sum across different attention values for each token.
att = att[:, :, :max_length, :max_length]
row_sums = np.sum(att, axis=2)
# Normalize
att /= row_sums[:, :, np.newaxis]
att_mat[i] = att
return att_mat |
Compute representation of the attention ready for the d3 visualization.
Args:
inp_text: list of strings, words to be displayed on the left of the vis
out_text: list of strings, words to be displayed on the right of the vis
enc_atts: numpy array, encoder self-attentions
[num_layers, batch_size, num_heads, enc_length, enc_length]
dec_atts: numpy array, decoder self-attentions
[num_layers, batch_size, num_heads, dec_length, dec_length]
encdec_atts: numpy array, encoder-decoder attentions
[num_layers, batch_size, num_heads, dec_length, enc_length]
Returns:
Dictionary of attention representations with the structure:
{
'all': Representations for showing all attentions at the same time.
'inp_inp': Representations for showing encoder self-attentions
'inp_out': Representations for showing encoder-decoder attentions
'out_out': Representations for showing decoder self-attentions
}
and each sub-dictionary has structure:
{
'att': list of inter attentions matrices, one for each attention head
'top_text': list of strings, words to be displayed on the left of the vis
'bot_text': list of strings, words to be displayed on the right of the vis
} | def _get_attention(inp_text, out_text, enc_atts, dec_atts, encdec_atts):
"""Compute representation of the attention ready for the d3 visualization.
Args:
inp_text: list of strings, words to be displayed on the left of the vis
out_text: list of strings, words to be displayed on the right of the vis
enc_atts: numpy array, encoder self-attentions
[num_layers, batch_size, num_heads, enc_length, enc_length]
dec_atts: numpy array, decoder self-attentions
[num_layers, batch_size, num_heads, dec_length, dec_length]
encdec_atts: numpy array, encoder-decoder attentions
[num_layers, batch_size, num_heads, dec_length, enc_length]
Returns:
Dictionary of attention representations with the structure:
{
'all': Representations for showing all attentions at the same time.
'inp_inp': Representations for showing encoder self-attentions
'inp_out': Representations for showing encoder-decoder attentions
'out_out': Representations for showing decoder self-attentions
}
and each sub-dictionary has structure:
{
'att': list of inter attentions matrices, one for each attention head
'top_text': list of strings, words to be displayed on the left of the vis
'bot_text': list of strings, words to be displayed on the right of the vis
}
"""
def get_full_attention(layer):
"""Get the full input+output - input+output attentions."""
enc_att = enc_atts[layer][0]
dec_att = dec_atts[layer][0]
encdec_att = encdec_atts[layer][0]
enc_att = np.transpose(enc_att, [0, 2, 1])
dec_att = np.transpose(dec_att, [0, 2, 1])
encdec_att = np.transpose(encdec_att, [0, 2, 1])
# [heads, query_length, memory_length]
enc_length = enc_att.shape[1]
dec_length = dec_att.shape[1]
num_heads = enc_att.shape[0]
first = np.concatenate([enc_att, encdec_att], axis=2)
second = np.concatenate(
[np.zeros((num_heads, dec_length, enc_length)), dec_att], axis=2)
full_att = np.concatenate([first, second], axis=1)
return [ha.T.tolist() for ha in full_att]
def get_inp_inp_attention(layer):
att = np.transpose(enc_atts[layer][0], (0, 2, 1))
return [ha.T.tolist() for ha in att]
def get_out_inp_attention(layer):
att = np.transpose(encdec_atts[layer][0], (0, 2, 1))
return [ha.T.tolist() for ha in att]
def get_out_out_attention(layer):
att = np.transpose(dec_atts[layer][0], (0, 2, 1))
return [ha.T.tolist() for ha in att]
def get_attentions(get_attention_fn):
num_layers = len(enc_atts)
return [get_attention_fn(i) for i in range(num_layers)]
attentions = {
'all': {
'att': get_attentions(get_full_attention),
'top_text': inp_text + out_text,
'bot_text': inp_text + out_text,
},
'inp_inp': {
'att': get_attentions(get_inp_inp_attention),
'top_text': inp_text,
'bot_text': inp_text,
},
'inp_out': {
'att': get_attentions(get_out_inp_attention),
'top_text': inp_text,
'bot_text': out_text,
},
'out_out': {
'att': get_attentions(get_out_out_attention),
'top_text': out_text,
'bot_text': out_text,
},
}
return attentions |
Decode a list of tokens to a unicode string.
Args:
tokens: a list of Unicode strings
Returns:
a unicode string | def decode(tokens):
"""Decode a list of tokens to a unicode string.
Args:
tokens: a list of Unicode strings
Returns:
a unicode string
"""
token_is_alnum = [t[0] in _ALPHANUMERIC_CHAR_SET for t in tokens]
ret = []
for i, token in enumerate(tokens):
if i > 0 and token_is_alnum[i - 1] and token_is_alnum[i]:
ret.append(u" ")
ret.append(token)
return "".join(ret) |
Reads files matching a wildcard pattern, yielding the contents.
Args:
filepattern: A wildcard pattern matching one or more files.
max_lines: If set, stop reading after reading this many lines.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespace from each line. Otherwise, treat each
file as a single string.
Yields:
The contents of the files as lines, if split_on_newlines is True, or
the entire contents of each file if False. | def _read_filepattern(filepattern, max_lines=None, split_on_newlines=True):
"""Reads files matching a wildcard pattern, yielding the contents.
Args:
filepattern: A wildcard pattern matching one or more files.
max_lines: If set, stop reading after reading this many lines.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespace from each line. Otherwise, treat each
file as a single string.
Yields:
The contents of the files as lines, if split_on_newlines is True, or
the entire contents of each file if False.
"""
filenames = sorted(tf.gfile.Glob(filepattern))
lines_read = 0
for filename in filenames:
with tf.gfile.Open(filename) as f:
if split_on_newlines:
for line in f:
yield line.strip()
lines_read += 1
if max_lines and lines_read >= max_lines:
return
else:
if max_lines:
doc = []
for line in f:
doc.append(line)
lines_read += 1
if max_lines and lines_read >= max_lines:
yield "".join(doc)
return
yield "".join(doc)
else:
yield f.read() |
Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespace from each line. Otherwise, treat each
file as a single string.
Returns:
a dictionary mapping token to count. | def corpus_token_counts(
text_filepattern, corpus_max_lines, split_on_newlines=True):
"""Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespace from each line. Otherwise, treat each
file as a single string.
Returns:
a dictionary mapping token to count.
"""
counts = collections.Counter()
for doc in _read_filepattern(
text_filepattern,
max_lines=corpus_max_lines,
split_on_newlines=split_on_newlines):
counts.update(encode(_native_to_unicode(doc)))
mlperf_log.transformer_print(
key=mlperf_log.PREPROC_VOCAB_SIZE, value=len(counts))
return counts |
Read a vocab file and return a dictionary of token counts.
Reads a two-column CSV file of tokens and their frequency in a dataset. The
tokens are presumed to be generated by encode() or the equivalent.
Args:
text_filepattern: A pattern matching one or more files.
max_lines: An integer; maximum total lines to read.
Returns:
a dictionary mapping token to count. | def vocab_token_counts(text_filepattern, max_lines):
"""Read a vocab file and return a dictionary of token counts.
Reads a two-column CSV file of tokens and their frequency in a dataset. The
tokens are presumed to be generated by encode() or the equivalent.
Args:
text_filepattern: A pattern matching one or more files.
max_lines: An integer; maximum total lines to read.
Returns:
a dictionary mapping token to count.
"""
ret = {}
for i, line in enumerate(
_read_filepattern(text_filepattern, max_lines=max_lines)):
if "," not in line:
tf.logging.warning("Malformed vocab line #%d '%s'", i, line)
continue
token, count = line.rsplit(",", 1)
ret[_native_to_unicode(token)] = int(count)
return ret |
Make a tf.train.Example for the problem.
features[input_feature_name] = input_ids
Also fills in any other required features with dummy values.
Args:
input_ids: list<int>.
problem: Problem.
input_feature_name: name of feature for input_ids.
Returns:
tf.train.Example | def _make_example(input_ids, problem, input_feature_name="inputs"):
"""Make a tf.train.Example for the problem.
features[input_feature_name] = input_ids
Also fills in any other required features with dummy values.
Args:
input_ids: list<int>.
problem: Problem.
input_feature_name: name of feature for input_ids.
Returns:
tf.train.Example
"""
features = {
input_feature_name:
tf.train.Feature(int64_list=tf.train.Int64List(value=input_ids))
}
# Fill in dummy values for any other required features that presumably
# will not actually be used for prediction.
data_fields, _ = problem.example_reading_spec()
for fname, ftype in data_fields.items():
if fname == input_feature_name:
continue
if not isinstance(ftype, tf.FixedLenFeature):
# Only FixedLenFeatures are required
continue
if ftype.default_value is not None:
# If there's a default value, no need to fill it in
continue
num_elements = functools.reduce(lambda acc, el: acc * el, ftype.shape, 1)
if ftype.dtype in [tf.int32, tf.int64]:
value = tf.train.Feature(
int64_list=tf.train.Int64List(value=[0] * num_elements))
if ftype.dtype in [tf.float32, tf.float64]:
value = tf.train.Feature(
float_list=tf.train.FloatList(value=[0.] * num_elements))
if ftype.dtype == tf.bytes:
value = tf.train.Feature(
bytes_list=tf.train.BytesList(value=[""] * num_elements))
tf.logging.info("Adding dummy value for feature %s as it is required by "
"the Problem.", fname)
features[fname] = value
return tf.train.Example(features=tf.train.Features(feature=features)) |
Wraps function to make grpc requests with runtime args. | def make_grpc_request_fn(servable_name, server, timeout_secs):
"""Wraps function to make grpc requests with runtime args."""
stub = _create_stub(server)
def _make_grpc_request(examples):
"""Builds and sends request to TensorFlow model server."""
request = predict_pb2.PredictRequest()
request.model_spec.name = servable_name
request.inputs["input"].CopyFrom(
tf.make_tensor_proto(
[ex.SerializeToString() for ex in examples], shape=[len(examples)]))
response = stub.Predict(request, timeout_secs)
outputs = tf.make_ndarray(response.outputs["outputs"])
scores = tf.make_ndarray(response.outputs["scores"])
assert len(outputs) == len(scores)
return [{ # pylint: disable=g-complex-comprehension
"outputs": output,
"scores": score
} for output, score in zip(outputs, scores)]
return _make_grpc_request |
Wraps function to make CloudML Engine requests with runtime args. | def make_cloud_mlengine_request_fn(credentials, model_name, version):
"""Wraps function to make CloudML Engine requests with runtime args."""
def _make_cloud_mlengine_request(examples):
"""Builds and sends requests to Cloud ML Engine."""
api = discovery.build("ml", "v1", credentials=credentials)
parent = "projects/%s/models/%s/versions/%s" % (cloud.default_project(),
model_name, version)
input_data = {
"instances": [{ # pylint: disable=g-complex-comprehension
"input": {
"b64": base64.b64encode(ex.SerializeToString())
}
} for ex in examples]
}
prediction = api.projects().predict(body=input_data, name=parent).execute()
return prediction["predictions"]
return _make_cloud_mlengine_request |
Encodes inputs, makes request to deployed TF model, and decodes outputs. | def predict(inputs_list, problem, request_fn):
"""Encodes inputs, makes request to deployed TF model, and decodes outputs."""
assert isinstance(inputs_list, list)
fname = "inputs" if problem.has_inputs else "targets"
input_encoder = problem.feature_info[fname].encoder
input_ids_list = [
_encode(inputs, input_encoder, add_eos=problem.has_inputs)
for inputs in inputs_list
]
examples = [_make_example(input_ids, problem, fname)
for input_ids in input_ids_list]
predictions = request_fn(examples)
output_decoder = problem.feature_info["targets"].encoder
outputs = [
(_decode(prediction["outputs"], output_decoder),
prediction["scores"])
for prediction in predictions
]
return outputs |
Basic 2-frame recurrent model with stochastic tower. | def next_frame_basic_recurrent():
"""Basic 2-frame recurrent model with stochastic tower."""
hparams = basic_stochastic.next_frame_basic_stochastic_discrete()
hparams.filter_double_steps = 2
hparams.hidden_size = 64
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 4
hparams.concat_internal_states = False
hparams.add_hparam("num_lstm_layers", 2)
hparams.add_hparam("num_lstm_filters", 256)
return hparams |
Creates experiment function. | def create_teacher_experiment(run_config, hparams, argv):
"""Creates experiment function."""
tf.logging.info("training teacher")
tf.logging.set_verbosity(tf.logging.INFO)
trainer_lib.set_random_seed(FLAGS.random_seed)
usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)
t2t_trainer.maybe_log_registry_and_exit()
if FLAGS.cloud_mlengine:
return cloud_mlengine.launch()
if FLAGS.generate_data:
t2t_trainer.generate_data()
if cloud_mlengine.job_dir():
FLAGS.output_dir = cloud_mlengine.job_dir()
if argv:
t2t_trainer.set_hparams_from_args(argv[1:])
hparams.distill_phase = "train"
exp_fn = t2t_trainer.create_experiment_fn()
exp = exp_fn(run_config, hparams)
return exp |
Generate source and target data from a single file. | def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
source_vocab_size, target_vocab_size):
"""Generate source and target data from a single file."""
filename = "parsing_{0}.pairs".format("train" if train else "dev")
source_vocab = generator_utils.get_or_generate_tabbed_vocab(
data_dir, tmp_dir, filename, 0,
prefix + "_source.tokens.vocab.%d" % source_vocab_size, source_vocab_size)
target_vocab = generator_utils.get_or_generate_tabbed_vocab(
data_dir, tmp_dir, filename, 1,
prefix + "_target.tokens.vocab.%d" % target_vocab_size, target_vocab_size)
pair_filepath = os.path.join(tmp_dir, filename)
return text_problems.text2text_generate_encoded(
text_problems.text2text_txt_tab_iterator(pair_filepath), source_vocab,
target_vocab) |
Generate source and target data from a single file. | def tabbed_parsing_character_generator(tmp_dir, train):
"""Generate source and target data from a single file."""
character_vocab = text_encoder.ByteTextEncoder()
filename = "parsing_{0}.pairs".format("train" if train else "dev")
pair_filepath = os.path.join(tmp_dir, filename)
return text_problems.text2text_generate_encoded(
text_problems.text2text_txt_tab_iterator(pair_filepath), character_vocab) |
Helper: make predictions and targets lists, check they match on length. | def _make_list(predictions, targets):
"""Helper: make predictions and targets lists, check they match on length."""
# Our models sometimes return predictions in lists, make it a list always.
# TODO(lukaszkaiser): make abstractions for nested structures and refactor.
if not isinstance(predictions, (list, tuple)):
if isinstance(targets, (list, tuple)):
raise ValueError("Targets are a list or tuple but predictions are not.")
predictions, targets = [predictions], [targets]
if len(predictions) != len(targets):
raise ValueError("Predictions and targets have different lengths.")
return list(predictions), list(targets) |
Mean of the inputs but counting only those where targets != mask_id. | def masked_mean(inputs, targets, mask_id=None):
"""Mean of the inputs but counting only those where targets != mask_id."""
inputs = [x.astype(np.float32) for x in inputs]
# We assume all elements in the list contribute equally.
# TODO(lukaszkaiser): remove this assumption (e.g., when masks differ).
length = len(inputs)
if mask_id is None:
# TODO(lukaszkaiser): can we just divide the sum by length? XLA optimizes?
return sum([np.mean(x) / length for x in inputs])
unmask = [1.0 - np.equal(t, mask_id).astype(np.float32) for t in targets]
return sum([np.sum(x * m) / (length * np.sum(m))
for x, m in zip(inputs, unmask)]) |
Calculate accuracy. | def accuracy(batch, model_predictions):
"""Calculate accuracy."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
correct = []
for (prediction, target) in zip(model_predictions, targets):
predicted_class = np.argmax(prediction, axis=-1)
correct.append(np.equal(predicted_class, target))
return masked_mean(correct, targets) |
Calculate negative log perplexity. | def neg_log_perplexity(batch, model_predictions):
"""Calculate negative log perplexity."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
xent = []
for (prediction, target) in zip(model_predictions, targets):
hot_target = layers.one_hot(target, prediction.shape[-1])
xent.append(np.sum(prediction * hot_target, axis=-1))
return masked_mean(xent, targets) |
Calculate loss. | def loss(params, batch, model_predict, rng):
"""Calculate loss."""
inputs, targets = batch
predictions = model_predict(inputs, params, rng=rng)
predictions, targets = _make_list(predictions, targets)
xent = []
for (pred, target) in zip(predictions, targets):
xent.append(np.sum(pred * layers.one_hot(target, pred.shape[-1]), axis=-1))
return - masked_mean(xent, targets) |
Restore State. | def restore_state(output_dir):
"""Restore State."""
params_file = os.path.join(output_dir, "model.pkl")
if not gfile.exists(params_file):
return State(step=None, params=None, history=trax_history.History())
with gfile.GFile(params_file, "rb") as f:
(params, step, history) = pickle.load(f)
log("Model loaded from %s at step %d" % (params_file, step))
logging.debug("From loaded model : history = %s", history)
return State(step=step, params=params, history=history) |
Save State and optionally gin config. | def save_state(state, output_dir, keep=False):
"""Save State and optionally gin config."""
params_file = os.path.join(output_dir, "model.pkl")
with gfile.GFile(params_file, "wb") as f:
pickle.dump((state.params, state.step, state.history), f)
if keep:
params_file = os.path.join(output_dir, "model_{}.pkl".format(state.step))
with gfile.GFile(params_file, "wb") as f:
pickle.dump((state.params, state.step, state.history), f)
log("Model saved to %s" % params_file, stdout=False) |
Evalaute on train and eval data, and log metrics. | def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng,
train_sw=None, eval_sw=None, history=None):
"""Evalaute on train and eval data, and log metrics."""
step_log(step, "Evaluation")
train_metrics, eval_metrics = [
evaluate( # pylint: disable=g-complex-comprehension
itertools.islice(input_stream(), eval_steps),
predict_fun,
_METRICS,
rng)
for input_stream in
[inputs.train_eval_stream, inputs.eval_stream]]
if train_sw:
log_metrics(train_metrics, train_sw, "train", step, history=history)
if eval_sw:
log_metrics(eval_metrics, eval_sw, "eval", step, history=history)
step_log(step, "Finished evaluation")
return train_metrics, eval_metrics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.