Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _prob_in_top_k(
clean_values, noisy_values, noise_stddev, noisy_top_values, k):
batch = tf.shape(clean_values)[0]
m = tf.shape(noisy_top_values)[1]
top_values_flat = tf.reshape(noisy_top_values, [-1])
# we want to compute the threshold that a particular va... | [
"Helper function to NoisyTopKGating.\n\n Computes the probability that value is in top k, given different random noise.\n\n This gives us a way of backpropagating from a loss that balances the number\n of times each expert is in the top k experts per example.\n\n In the case of no noise, pass in None for noise_... |
Please provide a description of the function:def cv_squared(x):
epsilon = 1e-10
float_size = tf.to_float(tf.size(x)) + epsilon
mean = tf.reduce_sum(x) / float_size
variance = tf.reduce_sum(tf.squared_difference(x, mean)) / float_size
return variance / (tf.square(mean) + epsilon) | [
"The squared coefficient of variation of a sample.\n\n Useful as a loss to encourage a positive distribution to be more uniform.\n Epsilons added for numerical stability.\n Returns 0 for an empty Tensor.\n\n Args:\n x: a `Tensor`.\n\n Returns:\n a `Scalar`.\n "
] |
Please provide a description of the function:def update_hparams_for_vq_gating(hparams):
hparams.add_hparam("z_size", 4)
hparams.add_hparam("noise_dev", 0.5)
# Bottleneck kinds supported: dense, vae, dvq.
hparams.add_hparam("bottleneck_kind", "dvq")
hparams.add_hparam("num_blocks", 1)
hparams.add_hparam("... | [
"VQ Gating hparams."
] |
Please provide a description of the function:def _my_top_k(x, k):
if k > 10:
return tf.nn.top_k(x, k)
values = []
indices = []
depth = tf.shape(x)[1]
for i in range(k):
values.append(tf.reduce_max(x, 1))
argmax = tf.argmax(x, 1)
indices.append(argmax)
if i + 1 < k:
x += tf.one_hot... | [
"GPU-compatible version of top-k that works for very small constant k.\n\n Calls argmax repeatedly.\n\n tf.nn.top_k is implemented for GPU, but the gradient, sparse_to_dense,\n seems not to be, so if we use tf.nn.top_k, then both the top_k and its\n gradient go on cpu. Once this is not an issue, this function ... |
Please provide a description of the function:def vq_gating(x,
num_experts,
k,
bneck,
hparams=None,
name="vq_gating"):
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
if hparams.use_scales:
scales = tf.get_variable(
"scale... | [
"VQ gating.\n\n Args:\n x: input Tensor with shape [batch_size, input_size]\n num_experts: an integer\n k: an integer - number of experts per example\n bneck: a bottleneck object\n hparams: optional hparams\n name: an optional string\n\n Returns:\n gates: a Tensor with shape [batch_size, num_... |
Please provide a description of the function:def noisy_top_k_gating(x,
num_experts,
train,
k=2,
initializer=tf.zeros_initializer(),
noisy_gating=True,
noise_epsilon=1e-2,
... | [
"Noisy top-k gating.\n\n See paper: https://arxiv.org/abs/1701.06538.\n\n Args:\n x: input Tensor with shape [batch_size, input_size]\n num_experts: an integer\n train: a boolean - we only add noise at training time.\n k: an integer - number of experts per example\n initializer: an initializer\n ... |
Please provide a description of the function:def map_ids(x, indices, map_fn):
indices = tf.reshape(indices, [-1])
t_i = tf.constant(0)
# batch_coordinates start at 0
t_batch_size = tf.reduce_max(indices) + 1
# ta_stack_out will store the intermediate results for each individual id
# As alternative to t... | [
"Apply a function to each coordinate ids of a multidimensional tensor.\n\n This allows to process each sequence of a batch independently. This is\n similar to tf.map_fn but with tensor where the batch dim has been flatten.\n\n Warning: The indices ids have to be contiguous and ordered in memory as the\n output ... |
Please provide a description of the function:def ffn_expert_fn(input_size,
hidden_sizes,
output_size,
hidden_activation=tf.nn.relu):
def my_fn(x):
layer_sizes = [input_size] + hidden_sizes + [output_size]
for i in range(1 + len(hidden_sizes)):
w =... | [
"Returns a function that creates a feed-forward network.\n\n Use this function to create the expert_fn argument to distributed_moe.\n\n Args:\n input_size: an integer\n hidden_sizes: a list of integers\n output_size: an integer\n hidden_activation: a unary function.\n\n Returns:\n a unary function... |
Please provide a description of the function:def flatten_all_but_last(a):
ret = tf.reshape(a, [-1, tf.shape(a)[-1]])
if not tf.executing_eagerly():
ret.set_shape([None] + a.get_shape().as_list()[-1:])
return ret | [
"Flatten all dimensions of a except the last."
] |
Please provide a description of the function:def local_moe(x,
train,
expert_fn,
num_experts,
k=1,
loss_coef=1e-2,
hparams=None,
pass_x=True,
pass_gates=False,
additional_dispatch_params=None,
... | [
"Call a local mixture of experts.\n\n Args:\n x: a tensors with shape [... , input_size]\n train: a boolean scalar.\n expert_fn: a function.\n num_experts: an integer - number of experts\n k: an integer - how many experts to use for each batch element\n loss_coef: a scalar - multiplier on load-ba... |
Please provide a description of the function:def local_moe_tpu(inputs,
hidden_size,
output_size,
num_experts,
loss_coef=1e-3,
overhead=1.0):
batch, length, input_size = common_layers.shape_list(inputs)[:]
# Each sequence se... | [
"Local mixture of experts that works well on TPU.\n\n See https://arxiv.org/abs/1701.06538\n\n There are num_experts expert networks, each containing a relu-activated\n hidden layer of size hidden_size, followed by an output projection.\n\n The number of parameters is thus:\n num_experts * (input_size * hidd... |
Please provide a description of the function:def reduce_by_device(parallelism, data, reduce_fn):
unique_devices = []
device_to_data = {}
for dev, datum in zip(parallelism.devices, data):
if dev not in device_to_data:
unique_devices.append(dev)
device_to_data[dev] = [datum]
else:
devic... | [
"Reduces data per device.\n\n This can be useful, for example, if we want to all-reduce n tensors on k<n\n devices (like during eval when we have only one device). We call\n reduce_by_device() to first sum the tensors per device, then call our usual\n all-reduce operation to create one sum per device, followed... |
Please provide a description of the function:def expand_by_device(original_parallelism, device_parallelism, data):
device_to_datum = {
device_parallelism.devices[i]: data[i]
for i in range(device_parallelism.n)}
return [device_to_datum[d] for d in original_parallelism.devices] | [
"Opposite of reduce_by_device().\n\n Args:\n original_parallelism: a expert_utils.Parallelism object.\n device_parallelism: a expert_utils.Parallelism object.\n data: a list of tensors with length device_parallelism.n\n\n Returns:\n a list of Tensors with length original_parallelism.n\n "
] |
Please provide a description of the function:def all_reduce_ring(x, parallelism, maybe_reduce=True, use_bfloat16=True):
if parallelism.n == 1:
return x
if maybe_reduce:
original_parallelism = parallelism
parallelism, x = reduce_by_device(parallelism, x, tf.add_n)
if parallelism.n == 1:
y = x
... | [
"Compute the sum of all Tensors and put the result everywhere.\n\n Assumes that the devices are connected in a ring.\n\n Args:\n x: a list of Tensors with length parallelism.n\n parallelism: a expert_utils.Parallelism object.\n maybe_reduce: a boolean - first reduce per device.\n use_bfloat16: a boole... |
Please provide a description of the function:def _maybe_repeat(self, x):
if isinstance(x, list):
assert len(x) == self.n
return x
else:
return [x] * self.n | [
"Utility function for processing arguments that are singletons or lists.\n\n Args:\n x: either a list of self.n elements, or not a list.\n\n Returns:\n a list of self.n elements.\n "
] |
Please provide a description of the function:def remove(self, x):
with tf.name_scope("pad_reduce/remove"):
x_shape = x.get_shape().as_list()
x = tf.gather_nd(
x,
indices=self.nonpad_ids,
)
if not tf.executing_eagerly():
# This is a hack but for some reason, g... | [
"Remove padding from the given tensor.\n\n Args:\n x (tf.Tensor): of shape [dim_origin,...]\n\n Returns:\n a tensor of shape [dim_compressed,...] with dim_compressed <= dim_origin\n "
] |
Please provide a description of the function:def restore(self, x):
with tf.name_scope("pad_reduce/restore"):
x = tf.scatter_nd(
indices=self.nonpad_ids,
updates=x,
shape=tf.concat([self.dim_origin, tf.shape(x)[1:]], axis=0),
)
return x | [
"Add padding back to the given tensor.\n\n Args:\n x (tf.Tensor): of shape [dim_compressed,...]\n\n Returns:\n a tensor of shape [dim_origin,...] with dim_compressed >= dim_origin. The\n dim is restored from the original reference tensor\n "
] |
Please provide a description of the function:def dispatch(self, inp):
inp = tf.gather(inp, self._batch_index)
return tf.split(inp, self._part_sizes_tensor, 0, num=self._num_experts) | [
"Create one input Tensor for each expert.\n\n The `Tensor` for a expert `i` contains the slices of `inp` corresponding\n to the batch elements `b` where `gates[b, i] > 0`.\n\n Args:\n inp: a `Tensor` of shape \"[batch_size, <extra_input_dims>]`\n Returns:\n a list of `num_experts` `Tensor`s wi... |
Please provide a description of the function:def combine(self, expert_out, multiply_by_gates=True):
# see comments on convert_gradient_to_tensor
stitched = common_layers.convert_gradient_to_tensor(
tf.concat(expert_out, 0))
if multiply_by_gates:
stitched *= tf.expand_dims(self._nonzero_ga... | [
"Sum together the expert output, weighted by the gates.\n\n The slice corresponding to a particular batch element `b` is computed\n as the sum over all experts `i` of the expert output, weighted by the\n corresponding gate values. If `multiply_by_gates` is set to False, the\n gate values are ignored.\n... |
Please provide a description of the function:def expert_to_gates(self):
return tf.split(
self._nonzero_gates, self._part_sizes_tensor, 0, num=self._num_experts) | [
"Gate values corresponding to the examples in the per-expert `Tensor`s.\n\n Returns:\n a list of `num_experts` one-dimensional `Tensor`s with type `tf.float32`\n and shapes `[expert_batch_size_i]`\n "
] |
Please provide a description of the function:def expert_to_batch_indices(self):
return tf.split(
self._batch_index, self._part_sizes_tensor, 0, num=self._num_experts) | [
"Batch indices corresponding to the examples in the per-expert `Tensor`s.\n\n Returns:\n a list of `num_experts` one-dimensional `Tensor`s with type `tf.int64`\n and shapes `[expert_batch_size_i]`\n "
] |
Please provide a description of the function:def dispatch(self, inp):
dispatched = self._dp(lambda a, b: a.dispatch(b), self._dispatchers, inp)
ret = self._ep(tf.concat, transpose_list_of_lists(dispatched), 0)
if ret[0].dtype == tf.float32:
# see comments on common_layers.convert_gradient_to_tens... | [
"Create one input Tensor for each expert.\n\n Args:\n inp: a list of length num_datashards `Tensor`s with shapes\n `[batch_size[d], <extra_input_dims>]`.\n Returns:\n a list of `num_experts` `Tensor`s with shapes\n `[num_examples[i], <extra_input_dims>]`.\n "
] |
Please provide a description of the function:def combine(self, expert_out, multiply_by_gates=True):
expert_part_sizes = tf.unstack(
tf.stack([d.part_sizes for d in self._dispatchers]),
num=self._ep.n,
axis=1)
# list of lists of shape [num_experts][num_datashards]
expert_output_p... | [
"Sum together the expert output, multiplied by the corresponding gates.\n\n Args:\n expert_out: a list of `num_experts` `Tensor`s, each with shape\n `[expert_batch_size_i, <extra_output_dims>]`.\n multiply_by_gates: a boolean.\n\n Returns:\n a list of num_datashards `Tensor`s with shapes... |
Please provide a description of the function:def expert_to_gates(self):
return self._ep(
tf.concat,
transpose_list_of_lists(
self._dp(lambda d: d.expert_to_gates(), self._dispatchers)), 0) | [
"Gate values corresponding to the examples in the per-expert `Tensor`s.\n\n Returns:\n a list of `num_experts` one-dimensional `Tensor`s of type `tf.float32`.\n "
] |
Please provide a description of the function:def dispatch(self, inp):
inp = tf.reshape(inp, [self._batch * self._length, -1])
# [batch, num_experts, expert_capacity, depth]
ret = tf.gather(inp, self._flat_indices)
return ret | [
"Send the inputs to the experts.\n\n Args:\n inp: a `Tensor` of shape \"[batch, length, depth]`\n Returns:\n a tensor with shape [batch, num_experts, expert_capacity, depth]\n "
] |
Please provide a description of the function:def combine(self, x):
depth = tf.shape(x)[-1]
x *= tf.expand_dims(self._nonpadding, -1)
ret = tf.unsorted_segment_sum(
x, self._flat_indices, num_segments=self._batch * self._length)
ret = tf.reshape(ret, [self._batch, self._length, depth])
r... | [
"Return the output from the experts.\n\n When one example goes to multiple experts, the outputs are summed.\n\n Args:\n x: a Tensor with shape [batch, num_experts, expert_capacity, depth]\n\n Returns:\n a `Tensor` with shape `[batch, length, depth]\n "
] |
Please provide a description of the function:def make_env(env_type, real_env, sim_env_kwargs):
return {
"real": lambda: real_env.new_like( # pylint: disable=g-long-lambda
batch_size=sim_env_kwargs["batch_size"],
store_rollouts=False,
),
"simulated": lambda: rl_utils.Simulated... | [
"Factory function for envs."
] |
Please provide a description of the function:def make_agent(
agent_type, env, policy_hparams, policy_dir, sampling_temp,
sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None,
batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs
):
if batch_size is None:
batch_si... | [
"Factory function for Agents."
] |
Please provide a description of the function:def collect_frames_for_random_starts(
storage_env, stacked_env, agent, frame_stack_size, random_starts_step_limit,
log_every_steps=None
):
del frame_stack_size
storage_env.start_new_epoch(0)
tf.logging.info(
"Collecting %d frames for random starts.", r... | [
"Collects frames from real env for random starts of simulated env."
] |
Please provide a description of the function:def make_agent_from_hparams(
agent_type, base_env, stacked_env, loop_hparams, policy_hparams,
planner_hparams, model_dir, policy_dir, sampling_temp, video_writers=()
):
def sim_env_kwargs_fn():
return rl.make_simulated_env_kwargs(
base_env, loop_hpar... | [
"Creates an Agent from hparams."
] |
Please provide a description of the function:def make_eval_fn_with_agent(
agent_type, eval_mode, planner_hparams, model_dir, log_every_steps=None,
video_writers=(), random_starts_step_limit=None
):
def eval_fn(env, loop_hparams, policy_hparams, policy_dir, sampling_temp):
base_env = env
env = ... | [
"Returns an out-of-graph eval_fn using the Agent API.",
"Eval function."
] |
Please provide a description of the function:def evaluate_world_model(
agent_type, loop_hparams, planner_hparams, model_dir, policy_dir,
random_starts_step_limit, debug_video_path, log_every_steps
):
if debug_video_path:
debug_video_path = os.path.join(debug_video_path, "0.avi")
storage_env = rl_uti... | [
"Evaluates the world model."
] |
Please provide a description of the function:def evaluate(
loop_hparams, planner_hparams, policy_dir, model_dir, eval_metrics_dir,
agent_type, eval_mode, eval_with_learner, log_every_steps, debug_video_path,
num_debug_videos=1, random_starts_step_limit=None,
report_fn=None, report_metric=None
):
if... | [
"Evaluate."
] |
Please provide a description of the function:def get_game_for_worker(map_name, directory_id):
if map_name == "v100unfriendly":
games = ["chopper_command", "boxing", "asterix", "seaquest"]
worker_per_game = 5
elif map_name == "human_nice":
games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE
worker_p... | [
"Get game for the given worker (directory) id."
] |
Please provide a description of the function:def get_open_spaces(board):
open_spaces = []
for i in range(3):
for j in range(3):
if board[i][j] == 0:
open_spaces.append(encode_pos(i, j))
return open_spaces | [
"Given a representation of the board, returns a list of open spaces."
] |
Please provide a description of the function:def get_reward_and_done(board):
# Returns (reward, done) where:
# reward: -1 means lost, +1 means win, 0 means draw or continuing.
# done: True if the game is over, i.e. someone won or it is a draw.
# Sum all rows ...
all_sums = [np.sum(board[i, :]) for i in ra... | [
"Given a representation of the board, returns reward and done."
] |
Please provide a description of the function:def decode_hparams(overrides=""):
hp = hparam.HParams(
save_images=False,
log_results=True,
extra_length=100,
min_length_ratio=0.0,
batch_size=0,
beam_size=4,
alpha=0.6,
eos_penalty=0.0,
block_size=0,
guess_and... | [
"Hyperparameters for decoding."
] |
Please provide a description of the function:def log_decode_results(inputs,
outputs,
problem_name,
prediction_idx,
inputs_vocab,
targets_vocab,
targets=None,
s... | [
"Log inference results."
] |
Please provide a description of the function:def decode_from_dataset(estimator,
problem_name,
hparams,
decode_hp,
decode_to_file=None,
dataset_split=None,
checkpoint_path=None)... | [
"Perform decoding from dataset."
] |
Please provide a description of the function:def decode_once(estimator,
problem_name,
hparams,
infer_input_fn,
decode_hp,
decode_to_file,
output_dir,
log_results=True,
checkpoint_path=None):
... | [
"Decodes once.\n\n Args:\n estimator: tf.estimator.Estimator instance. Used to generate encoded\n predictions.\n problem_name: str. Name of problem.\n hparams: HParams instance. HParams for model training.\n infer_input_fn: zero-arg function. Input function for estimator.\n decode_hp: HParams i... |
Please provide a description of the function:def decode_from_file(estimator,
filename,
hparams,
decode_hp,
decode_to_file=None,
checkpoint_path=None):
if not decode_hp.batch_size:
decode_hp.batch_size = 32
... | [
"Compute predictions on entries in filename and write them out."
] |
Please provide a description of the function:def _decode_filename(base_filename, problem_name, decode_hp):
if decode_hp.shards > 1:
base_filename = _add_shard_to_filename(base_filename, decode_hp)
if ("beam{beam}.alpha{alpha}.decodes".format(
beam=str(decode_hp.beam_size), alpha=str(decode_hp.alpha))
... | [
"Generates decode filename.\n\n Args:\n base_filename: A string, base of the decode filename.\n problem_name: A string, name of the problem.\n decode_hp: HParams for decoding.\n\n Returns:\n A string, produced decode filename.\n "
] |
Please provide a description of the function:def make_input_fn_from_generator(gen):
first_ex = six.next(gen)
flattened = tf.contrib.framework.nest.flatten(first_ex)
types = [t.dtype for t in flattened]
shapes = [[None] * len(t.shape) for t in flattened]
first_ex_list = [first_ex]
def py_func():
if f... | [
"Use py_func to yield elements from the given generator."
] |
Please provide a description of the function:def decode_interactively(estimator, hparams, decode_hp, checkpoint_path=None):
is_image = "image" in hparams.problem.name
is_text2class = isinstance(hparams.problem,
text_problems.Text2ClassProblem)
skip_eos_postprocess = (
is_ima... | [
"Interactive decoding."
] |
Please provide a description of the function:def _decode_batch_input_fn(num_decode_batches, sorted_inputs, vocabulary,
batch_size, max_input_size,
task_id=-1, has_input=True):
tf.logging.info(" batch %d" % num_decode_batches)
for b in range(num_decode_batches... | [
"Generator to produce batches of inputs."
] |
Please provide a description of the function:def _interactive_input_fn(hparams, decode_hp):
num_samples = decode_hp.num_samples if decode_hp.num_samples > 0 else 1
decode_length = decode_hp.extra_length
input_type = "text"
p_hparams = hparams.problem_hparams
has_input = "inputs" in p_hparams.modality
voc... | [
"Generator that reads from the terminal and yields \"interactive inputs\".\n\n Due to temporary limitations in tf.learn, if we don't want to reload the\n whole graph, then we are stuck encoding all of the input as one fixed-size\n numpy array.\n\n We yield int32 arrays with shape [const_array_size]. The format... |
Please provide a description of the function:def save_video(video, save_path_template):
try:
from PIL import Image # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires PIL library to be "
"installed: %s", e)
raise No... | [
"Save frames of the videos into files."
] |
Please provide a description of the function:def show_and_save_image(img, save_path):
try:
import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top
except ImportError as e:
tf.logging.warning(
"Showing and saving an image requires matplotlib to be "
"installed: %s", e)
r... | [
"Shows an image using matplotlib and saves it."
] |
Please provide a description of the function:def _get_language_modeling_inputs(filename,
delimiter="\n",
repeat=1,
append_space_to_final_punctionation=True):
with tf.gfile.Open(filename) as f:
text = f.read()
... | [
"Read a file of partial texts to continue.\n\n The purpose of append_space_to_final_punctionation is that SubwordTokenizer\n groups punctuation and the ensuing space in the same token. Adding a space\n causes the token to be completed.\n\n Args:\n filename: a string\n delimiter: a string\n repeat: an ... |
Please provide a description of the function:def _get_sorted_inputs(filename, delimiter="\n"):
tf.logging.info("Getting sorted inputs")
with tf.gfile.Open(filename) as f:
text = f.read()
records = text.split(delimiter)
inputs = [record.strip() for record in records]
# Strip the last empty line.
... | [
"Returning inputs sorted according to decreasing length.\n\n This causes inputs of similar lengths to be processed in the same batch,\n facilitating early stopping for short sequences.\n\n Longer sequences are sorted first so that if you're going to get OOMs,\n you'll see it in the first batch.\n\n Args:\n ... |
Please provide a description of the function:def _save_until_eos(ids, skip=False):
ids = ids.flatten()
if skip:
return ids
try:
index = list(ids).index(text_encoder.EOS_ID)
return ids[0:index]
except ValueError:
# No EOS_ID: return the array as-is.
return ids | [
"Strips everything after the first <EOS> token, which is normally 1."
] |
Please provide a description of the function:def _interactive_input_tensor_to_features_dict(feature_map, hparams):
inputs = tf.convert_to_tensor(feature_map["inputs"])
input_is_image = False if len(inputs.get_shape()) < 3 else True
x = inputs
if input_is_image:
x = tf.image.resize_images(x, [299, 299])
... | [
"Convert the interactive input format (see above) to a dictionary.\n\n Args:\n feature_map: dict with inputs.\n hparams: model hyperparameters\n\n Returns:\n a features dictionary, as expected by the decoder.\n "
] |
Please provide a description of the function:def _decode_input_tensor_to_features_dict(feature_map, hparams):
inputs = tf.convert_to_tensor(feature_map["inputs"])
input_is_image = False
x = inputs
p_hparams = hparams.problem_hparams
# Add a third empty dimension
x = tf.expand_dims(x, axis=[2])
x = tf.... | [
"Convert the interactive input format (see above) to a dictionary.\n\n Args:\n feature_map: dict with inputs.\n hparams: model hyperparameters\n\n Returns:\n a features dictionary, as expected by the decoder.\n "
] |
Please provide a description of the function:def run_postdecode_hooks(decode_hook_args, dataset_split):
hooks = decode_hook_args.problem.decode_hooks
if not hooks:
return
global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir)
if global_step is None:
tf.logging.info(
"Skipp... | [
"Run hooks after decodes have run."
] |
Please provide a description of the function:def dataset_splits(self):
return [{
"split": problem.DatasetSplit.TRAIN,
"shards": _TRAIN_SHARDS,
}, {
"split": problem.DatasetSplit.EVAL,
"shards": _DEV_SHARDS,
}] | [
"Splits of data to produce and number of output shards for each."
] |
Please provide a description of the function:def local_attention1d_spatial_decoder(x, kv_dim, heads_dim,
feedforward_dim, hparams):
batch_dim, length_dim, model_dim = x.shape.dims
blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length)
num_w_blocks_dim = mtf.Dimensio... | [
"Image Transformer decoder with local1D spatial layers."
] |
Please provide a description of the function:def local_attention2d_spatial_decoder(x, kv_dim, heads_dim,
feedforward_dim, hparams):
batch_dim, length_dim, model_dim = x.shape.dims
blocks_h_dim = mtf.Dimension("blocksh", hparams.block_height)
blocks_w_dim = mtf.Dimension("b... | [
"Image Transformer decoder with local2D spatial layers."
] |
Please provide a description of the function:def local_attention1d_masked_decoder(x, kv_dim, heads_dim,
feedforward_dim, hparams):
print(x)
_, length_dim, model_dim = x.shape.dims
for layer in range(hparams.num_decoder_layers):
layer_name = "decoder_layer_%d" % layer
... | [
"Image Transformer decoder with local1D masked layers."
] |
Please provide a description of the function:def mtf_image_transformer_base():
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.batch_size = 1
hparams.max_length = 3072
hparams.hidden_size = 256
hparams.label_smoothing = 0.0
# 8-w... | [
"Set of hyperparameters."
] |
Please provide a description of the function:def mtf_image_transformer_tiny():
hparams = mtf_image_transformer_base()
hparams.hidden_size = 128
hparams.d_ff = 256
hparams.batch_size = 4
hparams.num_encoder_layers = 1
hparams.num_decoder_layers = 4
hparams.num_heads = 4
hparams.attention_key_size = 12... | [
"Catch bugs locally..."
] |
Please provide a description of the function:def mtf_image_transformer_single():
hparams = mtf_image_transformer_tiny()
hparams.mesh_shape = ""
hparams.layout = ""
hparams.hidden_size = 32
hparams.filter_size = 32
hparams.batch_size = 1
hparams.num_encoder_layers = 1
hparams.num_decoder_layers = 1
... | [
"Small single parameters."
] |
Please provide a description of the function:def mtf_image_transformer_base_single():
hparams = mtf_image_transformer_base()
hparams.num_decoder_layers = 6
hparams.filter_size = 256
hparams.block_length = 128
hparams.mesh_shape = ""
hparams.layout = ""
return hparams | [
"Small single parameters."
] |
Please provide a description of the function:def mtf_image_transformer_tiny_spatial1d():
hparams = mtf_image_transformer_tiny()
hparams.num_decoder_layers = 6
hparams.filter_size = 128
hparams.block_height = 8
hparams.block_width = 8
hparams.attention_type = "local1d_spatial"
hparams.mesh_shape = ""
... | [
"Small single parameters."
] |
Please provide a description of the function:def mtf_image_transformer_base_cifar():
hparams = mtf_image_transformer_base()
hparams.mesh_shape = "batch:8"
hparams.layout = "batch:batch"
hparams.learning_rate_decay_steps = 13600 # one epoch
hparams.batch_size = 32
hparams.num_heads = 4
hparams.num_deco... | [
"Data parallel CIFAR parameters."
] |
Please provide a description of the function:def mtf_image_transformer_cifar_4x():
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "batch:32"
hparams.layout = "batch:batch"
hparams.batch_size = 128
return hparams | [
"Data parallel CIFAR parameters."
] |
Please provide a description of the function:def mtf_image_transformer_cifar_mp_4x():
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "model:4;batch:8"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 32
hparams.num_heads = 8
hparams.d_ff = 8192
return hparam... | [
"Data parallel CIFAR parameters."
] |
Please provide a description of the function:def mtf_image_transformer_base_imagenet():
hparams = mtf_image_transformer_base_cifar()
hparams.mesh_shape = "batch:32"
hparams.layout = "batch:batch"
hparams.batch_size = 128
hparams.d_ff = 2048
hparams.hidden_size = 512
hparams.num_decoder_layers = 12
hp... | [
"Data parallel CIFAR parameters."
] |
Please provide a description of the function:def mtf_image_transformer_base_imagenet_mp():
hparams = mtf_image_transformer_base_imagenet()
hparams.mesh_shape = "model:4;batch:8"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 32
hparams.num_heads = 8
hparams.d_ff = 8192
hpara... | [
"Model parallel ImageNet parameters."
] |
Please provide a description of the function:def mtf_image_transformer_base_imagenet_mp128():
hparams = mtf_image_transformer_base_imagenet()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 8
hparams.img_len = 128
hparams.block_length = 12... | [
"Model parallel ImageNet parameters."
] |
Please provide a description of the function:def mtf_image_transformer_base_imagenet_mp_sp():
hparams = mtf_image_transformer_base_imagenet_mp128()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;num_wblocks:model"
hparams.batch_size = 8
hparams.img_len = 128
hparams.block... | [
"Model parallel ImageNet parameters."
] |
Please provide a description of the function:def mtf_image_transformer_base_imagenet_mp64():
hparams = mtf_image_transformer_base_imagenet()
hparams.mesh_shape = "model:8;batch:4"
hparams.layout = "batch:batch;d_ff:model;heads:model"
hparams.batch_size = 8
hparams.img_len = 64
hparams.num_decoder_layers ... | [
"Model parallel ImageNet parameters."
] |
Please provide a description of the function:def create_degrees(input_dim,
hidden_dims,
input_order='left-to-right',
hidden_order='left-to-right'):
if (isinstance(input_order, str) and
input_order not in ('random', 'left-to-right', 'right-to-left')):
... | [
"Returns a list of degree vectors, one for each input and hidden layer.\n\n A unit with degree d can only receive input from units with degree < d. Output\n units always have the same degree as their associated input unit.\n\n Args:\n input_dim: Number of inputs.\n hidden_dims: list with the number of hidd... |
Please provide a description of the function:def create_masks(input_dim,
hidden_dims,
input_order='left-to-right',
hidden_order='left-to-right'):
degrees = create_degrees(input_dim, hidden_dims, input_order, hidden_order)
masks = []
# Create input-to-hidden an... | [
"Returns a list of binary mask matrices respecting autoregressive ordering.\n\n Args:\n input_dim: Number of inputs.\n hidden_dims: list with the number of hidden units per layer. It does not\n include the output layer; those number of units will always be set to\n input_dim downstream. Each hidden... |
Please provide a description of the function:def sinkhorn(inputs, n_iters=20):
vocab_size = tf.shape(inputs)[-1]
log_alpha = tf.reshape(inputs, [-1, vocab_size, vocab_size])
for _ in range(n_iters):
log_alpha -= tf.reshape(tf.reduce_logsumexp(log_alpha, axis=2),
[-1, vocab_size... | [
"Performs incomplete Sinkhorn normalization to inputs.\n\n By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix\n with positive entries can be turned into a doubly-stochastic matrix\n (i.e. its rows and columns add up to one) via the succesive row and column\n normalization.\n -To ensure... |
Please provide a description of the function:def TransformedRandomVariable(random_variable, # pylint: disable=invalid-name
reversible_layer,
name=None,
sample_shape=(),
value=None):
return ed.Ra... | [
"Random variable for f(x), where x ~ p(x) and f is reversible."
] |
Please provide a description of the function:def log_det_jacobian(self, inputs):
del inputs # unused
# Number of events is number of all elements excluding the batch and
# channel dimensions.
num_events = tf.reduce_prod(tf.shape(inputs)[1:-1])
log_det_jacobian = num_events * tf.reduce_sum(self... | [
"Returns log det | dx / dy | = num_events * sum log | scale |."
] |
Please provide a description of the function:def slice_hidden(self, x):
x_sliced = tf.reshape(
x, shape=[-1, self.hparams.num_blocks, self.hparams.block_dim])
return x_sliced | [
"Slice encoder hidden state into block_dim.\n\n Args:\n x: Encoder hidden state of shape [-1, hidden_size].\n\n Returns:\n Sliced states of shape [-1, num_blocks, block_dim].\n "
] |
Please provide a description of the function:def nearest_neighbor(self, x, means):
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keep_dims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keep_dims=True)
scalar_prod = tf.matmul(
tf.transpose(x, perm=[1, 0, 2]), tf.transpose(mea... | [
"Find the nearest element in means to elements in x.\n\n Args:\n x: Batch of encoder continuous latent states sliced/projected into\n shape [-1, num_blocks, block_dim].\n means: Embedding means of shape.\n\n Returns:\n Tensor with nearest element in mean encoded in one-hot notatio... |
Please provide a description of the function:def embedding_lookup(self, x, means):
x_means_hot = self.nearest_neighbor(x, means)
x_means_hot_flat = tf.reshape(
x_means_hot, [-1, self.hparams.num_blocks, self.hparams.block_v_size])
x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2... | [
"Compute nearest neighbors and loss for training the embeddings.\n\n Args:\n x: Batch of encoder continuous latent states sliced/projected into\n shape\n [-1, num_blocks, block_dim].\n means: Embedding means.\n\n Returns:\n The nearest neighbor in one hot form, the nearest n... |
Please provide a description of the function:def int_to_bit(self, x_int, num_bits, base=2):
x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
# pylint: disable=g-complex-comprehension
x_labels = [
tf.floormod(
tf.floordiv(tf.to_int32(x_l),
tf.to_int32(base)**... | [
"Turn x_int representing numbers into a bitwise (lower-endian) tensor.\n\n Args:\n x_int: Tensor containing integer to be converted into base\n notation.\n num_bits: Number of bits in the representation.\n base: Base of the representation.\n\n Returns:\n Corresponding number... |
Please provide a description of the function:def embed(self, x):
shape_x = common_layers.shape_list(x)
x_flat = tf.reshape(x, [-1, 1])
c = self.int_to_bit(x_flat, num_bits=self.hparams.z_size, base=2)
shape = common_layers.shape_list(c)
new_shape = shape
new_shape.append(self.hparams.num_bl... | [
"Embedding function that takes discrete latent and returns embedding.\n\n Args:\n x: Input to the discretization bottleneck.\n Returns:\n Continuous embedding to be passed on to the decoder.\n\n Raises:\n ValueError: For unknown or missing arguments.\n "
] |
Please provide a description of the function:def discrete_bottleneck(self, x):
x_reshaped = self.slice_hidden(x)
x_means_hot = []
x_means = 0
loss = 0
x_means_hot, x_means, q_loss, e_loss = self.embedding_lookup(
x_reshaped, self.means)
if self.hparams.ema:
tf.logging.info("U... | [
"Discretization bottleneck for latent variables.\n\n Args:\n x: Input to the discretization bottleneck.\n\n Returns:\n Embedding to pass to the decoder, discrete latent, loss, and the\n embedding\n function.\n\n Raises:\n ValueError: If projection_tensors is None for resh... |
Please provide a description of the function:def mimic_adam_with_adafactor(hparams):
assert "adam" in hparams.optimizer
hparams.optimizer = "adafactor"
hparams.optimizer_adafactor_beta1 = hparams.optimizer_adam_beta1
hparams.optimizer_adafactor_beta2 = hparams.optimizer_adam_beta2
hparams.optimizer_adafact... | [
"Switch from Adam to Adafactor, approximating the behavior of Adam.\n\n Some minor things may be different, like epsilon and beta1 correction.\n\n Args:\n hparams: model hyperparameters where \"adam\" in hparams.optimizer\n "
] |
Please provide a description of the function:def afx_adam():
hparams = transformer.transformer_base_v2()
hparams.optimizer_adam_beta1 = 0.9
hparams.optimizer_adam_beta2 = 0.999
hparams.symbol_modality_num_shards = 1
hparams.batch_size = 2048
hparams.optimizer = "adam"
hparams.learning_rate_schedule = (... | [
"Old version - Adam."
] |
Please provide a description of the function:def afx_adafactor():
hparams = afx_adam()
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_warmup_steps = 10000
return hparams | [
"Adafactor with recommended learning rate schedule."
] |
Please provide a description of the function:def afx_small():
hparams = transformer.transformer_tpu()
hparams.filter_size = 1024
hparams.num_heads = 4
hparams.num_hidden_layers = 3
hparams.batch_size = 512
return hparams | [
"Small transformer model with small batch size for fast step times."
] |
Please provide a description of the function:def next_frame_emily():
hparams = sv2p_params.next_frame_sv2p()
hparams.video_num_input_frames = 2
hparams.video_num_target_frames = 10
hparams.learning_rate_constant = 1e-4
seq_length = hparams.video_num_input_frames + hparams.video_num_target_frames
# The la... | [
"Emily's model hparams."
] |
Please provide a description of the function:def main(_):
if FLAGS.subword_text_encoder_filename:
encoder = text_encoder.SubwordTextEncoder(
FLAGS.subword_text_encoder_filename)
elif FLAGS.token_text_encoder_filename:
encoder = text_encoder.TokenTextEncoder(FLAGS.token_text_encoder_filename)
el... | [
"Convert a file to examples."
] |
Please provide a description of the function:def example_reading_spec(self):
video_fields, video_decoders = (
video_utils.VideoProblem.example_reading_spec(self))
env_fields, env_decoders = env_problem.EnvProblem.example_reading_spec(self)
# Remove raw observations field since we want to captu... | [
"Return a mix of env and video data fields and decoders."
] |
Please provide a description of the function:def _generate_time_steps(self, trajectory_list):
for time_step in env_problem.EnvProblem._generate_time_steps(
self, trajectory_list):
# Convert the rendered observations from numpy to png format.
frame_np = np.array(time_step.pop(env_problem.OBS... | [
"Transforms time step observations to frames of a video."
] |
Please provide a description of the function:def txt_line_iterator(txt_path):
with tf.gfile.Open(txt_path) as f:
for line in f:
yield line.strip() | [
"Iterate through lines of file."
] |
Please provide a description of the function:def text2text_txt_iterator(source_txt_path, target_txt_path):
for inputs, targets in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path)):
yield {"inputs": inputs, "targets": targets} | [
"Yield dicts for Text2TextProblem.generate_samples from lines of files."
] |
Please provide a description of the function:def text2text_distill_iterator(source_txt_path, target_txt_path,
distill_txt_path):
for inputs, targets, dist_targets in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path),
txt_line_iterator(distill_txt... | [
"Yield dicts for Text2TextProblem.generate_samples from lines of files."
] |
Please provide a description of the function:def text2class_txt_iterator(source_txt_path, label_txt_path, class_strs=None):
if class_strs:
class_strs = dict([(s, i) for i, s in enumerate(class_strs)])
for inputs, label in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(label_txt_path)):
... | [
"Yield dicts for Text2ClassProblem.generate_samples from lines of files.\n\n Args:\n source_txt_path: txt file with record per line.\n label_txt_path: txt file with label per line, either as int or str. If\n string, must provide class_strs.\n class_strs: list<str> of class label names. Must be in cor... |
Please provide a description of the function:def text2text_txt_tab_iterator(txt_path):
for line in txt_line_iterator(txt_path):
if line and "\t" in line:
parts = line.split("\t", 1)
inputs, targets = parts[:2]
yield {"inputs": inputs.strip(), "targets": targets.strip()} | [
"Yield dicts for Text2TextProblem.generate_samples from lines of txt_path.\n\n Args:\n txt_path: path to txt file with a record per line, source and target\n are tab-separated.\n\n Yields:\n {\"inputs\": inputs, \"targets\": targets}\n "
] |
Please provide a description of the function:def text2text_generate_encoded(sample_generator,
vocab,
targets_vocab=None,
has_inputs=True,
inputs_prefix="",
targets_p... | [
"Encode Text2Text samples from the generator with the vocab."
] |
Please provide a description of the function:def _pack_fn(self):
if not self.packed_length:
return None
def my_fn(records):
examples = []
for record in records:
x = tf.train.Example()
x.ParseFromString(record)
example_dict = {}
if self.has_inputs:
... | [
"For packed datasets, returns a function to pack examples.\n\n Returns:\n None or a function from list of TFRecords to list of TFRecords\n ",
"Function from list of TFRecords to list of TFRecords."
] |
Please provide a description of the function:def _maybe_pack_examples(self, generator):
if not self.packed_length:
return generator
return generator_utils.pack_examples(
generator,
self.has_inputs,
self.packed_length,
spacing=self.packed_spacing,
chop_long_sequ... | [
"Wraps generator with packer if self.packed_length."
] |
Please provide a description of the function:def text_filepaths_for_task(self, tmp_dir, task_id):
assert task_id >= 0
assert task_id < self.num_train_shards + self.num_dev_shards
if task_id < self.num_train_shards:
return [
f for i, f in enumerate(self.train_text_filepaths(tmp_dir))
... | [
"List of input filepaths for a particular training or dev shard.\n\n Args:\n tmp_dir: a string\n task_id: an integer less than self.num_shards\n Returns:\n a list of tuples (filepath, start_pos, num_bytes)\n "
] |
Please provide a description of the function:def filepath_to_unicode_strings(self, filepath):
f = tf.gfile.Open(filepath)
b = f.read()
yield text_encoder.to_unicode_ignore_errors(b) | [
"Read text out of an input file.\n\n The default just reads the text, converts to unicode and yields one\n unicode string.\n\n Subclasses can override this function in order to preprocess, and can\n yield any number of strings.\n\n Args:\n filepath: a string\n Yields:\n unicode strings.\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.