Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def embedding(x,
vocab_size,
dense_size,
name=None,
reuse=None,
multiplier=1.0,
symbol_dropout_rate=0.0,
embedding_var=None,
dtype=tf.float32):
with tf.variab... | [
"Embed x of type int64 into dense vectors, reducing to max 4 dimensions."
] |
Please provide a description of the function:def shift_right(x, pad_value=None):
if pad_value is None:
shifted_targets = tf.pad(x, [[0, 0], [1, 0], [0, 0], [0, 0]])[:, :-1, :, :]
else:
shifted_targets = tf.concat([pad_value, x], axis=1)[:, :-1, :, :]
return shifted_targets | [
"Shift the second dimension of x right by one."
] |
Please provide a description of the function:def shift_right_3d(x, pad_value=None):
if pad_value is None:
shifted_targets = tf.pad(x, [[0, 0], [1, 0], [0, 0]])[:, :-1, :]
else:
shifted_targets = tf.concat([pad_value, x], axis=1)[:, :-1, :]
return shifted_targets | [
"Shift the second dimension of x right by one."
] |
Please provide a description of the function:def shift_right_2d(x, pad_value=None):
if pad_value is None:
shifted_targets = tf.pad(x, [[0, 0], [1, 0]])[:, :-1]
else:
shifted_targets = tf.concat([pad_value, x], axis=1)[:, :-1]
return shifted_targets | [
"Shift the second dimension of x right by one."
] |
Please provide a description of the function:def conv_stride2_multistep(x, nbr_steps, output_filters, name=None, reuse=None):
with tf.variable_scope(
name, default_name="conv_stride2_multistep", values=[x], reuse=reuse):
if nbr_steps == 0:
out = conv(x, output_filters, (1, 1))
return out, [ou... | [
"Use a strided convolution to downsample x by 2, `nbr_steps` times.\n\n We use stride and filter size 2 to avoid the checkerboard problem of deconvs.\n As detailed in http://distill.pub/2016/deconv-checkerboard/.\n\n Args:\n x: a `Tensor` with shape `[batch, spatial, depth]` or\n `[batch, spatial_1, spati... |
Please provide a description of the function:def deconv_stride2_multistep(x,
nbr_steps,
output_filters,
name=None,
reuse=None):
with tf.variable_scope(
name, default_name="deconv_stride2_multis... | [
"Use a deconvolution to upsample x by 2**`nbr_steps`.\n\n Args:\n x: a `Tensor` with shape `[batch, spatial, depth]` or\n `[batch, spatial_1, spatial_2, depth]`\n nbr_steps: an int specifying the number of doubling upsample rounds to\n apply.\n output_filters: an int specifying the filter count fo... |
Please provide a description of the function:def conv_internal(conv_fn, inputs, filters, kernel_size, **kwargs):
static_shape = inputs.get_shape()
if not static_shape or len(static_shape) != 4:
raise ValueError("Inputs to conv must have statically known rank 4. "
"Shape: " + str(static_s... | [
"Conditional conv_fn making kernel 1d or 2d depending on inputs shape.",
"Call conv2d but add suffix to name."
] |
Please provide a description of the function:def subseparable_conv(inputs, filters, kernel_size, **kwargs):
def conv_fn(inputs, filters, kernel_size, **kwargs):
separability = None
if "separability" in kwargs:
separability = kwargs.pop("separability")
if separability:
parts = []
... | [
"Sub-separable convolution. If separability == 0 it's a separable_conv.",
"Sub-separable convolution, splits into separability-many blocks."
] |
Please provide a description of the function:def tpu_conv1d(inputs, filters, kernel_size, padding="SAME", name="tpu_conv1d"):
if kernel_size == 1:
return dense(inputs, filters, name=name, use_bias=True)
if padding == "SAME":
assert kernel_size % 2 == 1
first_offset = -((kernel_size - 1) // 2)
else:... | [
"Version of conv1d that works on TPU (as of 11/2017).\n\n Args:\n inputs: a Tensor with shape [batch, length, input_depth].\n filters: an integer.\n kernel_size: an integer.\n padding: a string - \"SAME\" or \"LEFT\".\n name: a string.\n\n Returns:\n a Tensor with shape [batch, length, filters].... |
Please provide a description of the function:def layer_norm_vars(filters):
scale = tf.get_variable(
"layer_norm_scale", [filters], initializer=tf.ones_initializer())
bias = tf.get_variable(
"layer_norm_bias", [filters], initializer=tf.zeros_initializer())
return scale, bias | [
"Create Variables for layer norm."
] |
Please provide a description of the function:def layer_norm_compute(x, epsilon, scale, bias, layer_collection=None):
# Save these before they get converted to tensors by the casting below
params = (scale, bias)
epsilon, scale, bias = [cast_like(t, x) for t in [epsilon, scale, bias]]
mean = tf.reduce_mean(x... | [
"Layer norm raw computation."
] |
Please provide a description of the function:def layer_norm(x,
filters=None,
epsilon=1e-6,
name=None,
reuse=None,
layer_collection=None):
if filters is None:
filters = shape_list(x)[-1]
with tf.variable_scope(
name, default_name... | [
"Layer normalize the tensor x, averaging over the last dimension."
] |
Please provide a description of the function:def group_norm(x, filters=None, num_groups=8, epsilon=1e-5):
x_shape = shape_list(x)
if filters is None:
filters = x_shape[-1]
assert len(x_shape) == 4
assert filters % num_groups == 0
# Prepare variables.
scale = tf.get_variable(
"group_norm_scale",... | [
"Group normalization as in https://arxiv.org/abs/1803.08494."
] |
Please provide a description of the function:def noam_norm(x, epsilon=1.0, name=None):
with tf.name_scope(name, default_name="noam_norm", values=[x]):
shape = x.get_shape()
ndims = len(shape)
return (tf.nn.l2_normalize(x, ndims - 1, epsilon=epsilon) * tf.sqrt(
to_float(shape[-1]))) | [
"One version of layer normalization."
] |
Please provide a description of the function:def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None):
if filters is None:
filters = shape_list(x)[-1]
with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse):
scale = tf.get_variable(
"l2_norm_scale", [filters], initi... | [
"Layer normalization with l2 norm."
] |
Please provide a description of the function:def apply_spectral_norm(x):
weights_shape = shape_list(x)
other, num_filters = tf.reduce_prod(weights_shape[:-1]), weights_shape[-1]
# Reshape into a 2-D matrix with outer size num_filters.
weights_2d = tf.reshape(x, (other, num_filters))
# v = Wu / ||W u||
... | [
"Normalizes x using the spectral norm.\n\n The implementation follows Algorithm 1 of\n https://arxiv.org/abs/1802.05957. If x is not a 2-D Tensor, then it is\n reshaped such that the number of channels (last-dimension) is the same.\n\n Args:\n x: Tensor with the last dimension equal to the number of filters.... |
Please provide a description of the function:def apply_norm(x, norm_type, depth, epsilon, layer_collection=None):
if layer_collection is not None:
assert norm_type == "layer"
if norm_type == "layer":
return layer_norm(
x, filters=depth, epsilon=epsilon, layer_collection=layer_collection)
if nor... | [
"Apply Normalization."
] |
Please provide a description of the function:def zero_add(previous_value, x, name=None, reuse=None):
with tf.variable_scope(name, default_name="zero_add", reuse=reuse):
gamma = tf.get_variable("gamma", (), initializer=tf.zeros_initializer())
return previous_value + gamma * x | [
"Resnet connection with zero initialization.\n\n Another type of resnet connection which returns previous_value + gamma * x.\n gamma is a trainable scalar and initialized with zero. It is useful when a\n module is plugged into a trained model and we want to make sure it matches the\n original model's performanc... |
Please provide a description of the function:def layer_prepostprocess(previous_value,
x,
sequence,
dropout_rate,
norm_type,
depth,
epsilon,
defau... | [
"Apply a sequence of functions to the input or output of a layer.\n\n The sequence is specified as a string which may contain the following\n characters:\n a: add previous_value\n n: apply normalization\n d: apply dropout\n z: zero add\n\n For example, if sequence==\"dna\", then the output is\n pr... |
Please provide a description of the function:def layer_preprocess(layer_input, hparams, layer_collection=None):
assert "a" not in hparams.layer_preprocess_sequence, (
"No residual connections allowed in hparams.layer_preprocess_sequence")
assert "z" not in hparams.layer_preprocess_sequence, (
"No res... | [
"Apply layer preprocessing.\n\n See layer_prepostprocess() for details.\n\n A hyperparameters object is passed for convenience. The hyperparameters\n that may be used are:\n\n layer_preprocess_sequence\n layer_prepostprocess_dropout\n norm_type\n hidden_size\n norm_epsilon\n\n Args:\n layer_i... |
Please provide a description of the function:def layer_postprocess(layer_input, layer_output, hparams):
return layer_prepostprocess(
layer_input,
layer_output,
sequence=hparams.layer_postprocess_sequence,
dropout_rate=hparams.layer_prepostprocess_dropout,
norm_type=hparams.norm_type,
... | [
"Apply layer postprocessing.\n\n See layer_prepostprocess() for details.\n\n A hyperparameters object is passed for convenience. The hyperparameters\n that may be used are:\n\n layer_postprocess_sequence\n layer_prepostprocess_dropout\n norm_type\n hidden_size\n norm_epsilon\n\n Args:\n layer... |
Please provide a description of the function:def conv_block_internal(conv_fn,
inputs,
filters,
dilation_rates_and_kernel_sizes,
first_relu=True,
use_elu=False,
separabilities=N... | [
"A block of convolutions.\n\n Args:\n conv_fn: convolution function, e.g. conv or separable_conv.\n inputs: a Tensor\n filters: an Integer\n dilation_rates_and_kernel_sizes: a list of tuples (dilation, (k_w, k_h))\n first_relu: whether to do a relu at start (defaults to True)\n use_elu: whether t... |
Please provide a description of the function:def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
return conv_block_internal(conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | [
"A block of standard 2d convolutions."
] |
Please provide a description of the function:def conv1d_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):
return conv_block_internal(conv1d, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | [
"A block of standard 1d convolutions."
] |
Please provide a description of the function:def separable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes,
**kwargs):
return conv_block_internal(separable_conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | [
"A block of separable convolutions."
] |
Please provide a description of the function:def subseparable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes,
**kwargs):
return conv_block_internal(subseparable_conv, inputs, filters,
dilation_rates_and_kernel_sizes, **kwargs) | [
"A block of separable convolutions."
] |
Please provide a description of the function:def pool(inputs, window_size, pooling_type, padding, strides=(1, 1)):
with tf.name_scope("pool", values=[inputs]):
static_shape = inputs.get_shape()
if not static_shape or len(static_shape) != 4:
raise ValueError("Inputs to conv must have statically known ... | [
"Pooling (supports \"LEFT\")."
] |
Please provide a description of the function:def conv_block_downsample(x,
kernel,
strides,
padding,
separability=0,
name=None,
reuse=None):
with tf.variable_sc... | [
"Implements a downwards-striding conv block, like Xception exit flow."
] |
Please provide a description of the function:def get_timing_signal(length,
min_timescale=1,
max_timescale=1e4,
num_timescales=16):
positions = to_float(tf.range(length))
log_timescale_increment = (
math.log(max_timescale / min_timescale) / (... | [
"Create Tensor of sinusoids of different frequencies.\n\n Args:\n length: Length of the Tensor to create, i.e. Number of steps.\n min_timescale: a float\n max_timescale: a float\n num_timescales: an int\n\n Returns:\n Tensor of shape (length, 2*num_timescales)\n "
] |
Please provide a description of the function:def add_timing_signal(x, min_timescale=1, max_timescale=1e4, num_timescales=16):
length = shape_list(x)[1]
depth = shape_list(x)[3]
signal = get_timing_signal(length, min_timescale, max_timescale,
num_timescales)
padded_signal = tf.pad... | [
"Adds a bunch of sinusoids of different frequencies to a Tensor.\n\n This allows attention to learn to use absolute and relative positions.\n The timing signal should be added to some precursor of both the source\n and the target of the attention.\n\n The use of relative position is possible because sin(x+y) an... |
Please provide a description of the function:def mask_from_embedding(emb):
return weights_nonzero(tf.reduce_sum(tf.abs(emb), axis=3, keepdims=True)) | [
"Input embeddings -> padding mask.\n\n We have hacked symbol_modality to return all-zero embeddings for padding.\n Returns a mask with 0.0 in the padding positions and 1.0 elsewhere.\n\n Args:\n emb: a Tensor with shape [batch, width, height, depth].\n Returns:\n a 0.0/1.0 Tensor with shape [batch, width,... |
Please provide a description of the function:def length_from_embedding(emb):
return tf.cast(tf.reduce_sum(mask_from_embedding(emb), [1, 2, 3]), tf.int32) | [
"Compute the length of each sequence in the batch.\n\n Args:\n emb: a sequence embedding Tensor with shape [batch, max_time, 1, depth].\n Returns:\n a Tensor with shape [batch].\n "
] |
Please provide a description of the function:def relu_density_logit(x, reduce_dims):
frac = tf.reduce_mean(to_float(x > 0.0), reduce_dims)
scaled = tf.log(frac + math.exp(-10)) - tf.log((1.0 - frac) + math.exp(-10))
return scaled | [
"logit(density(x)).\n\n Useful for histograms.\n\n Args:\n x: a Tensor, typically the output of tf.relu\n reduce_dims: a list of dimensions\n\n Returns:\n a Tensor\n "
] |
Please provide a description of the function:def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask):
if (kernel_size != 1 and kernel_size != (1, 1) and
nonpadding_mask is not None):
while nonpadding_mask.get_shape().ndims < inputs.get_shape().ndims:
nonpadding_mask = tf.expand_dims(nonpad... | [
"If necessary, zero out inputs to a conv for padding positions.\n\n Args:\n inputs: a Tensor with shape [batch, length, ...]\n kernel_size: an integer or pair of integers\n nonpadding_mask: a Tensor with shape [batch, length]\n\n Returns:\n Tensor of the same shape as inputs.\n "
] |
Please provide a description of the function:def dense_relu_dense(inputs,
filter_size,
output_size,
output_activation=None,
dropout=0.0,
dropout_broadcast_dims=None,
layer_collection=None,
... | [
"Hidden layer with RELU activation followed by linear projection."
] |
Please provide a description of the function:def dense_dropconnect(inputs,
output_size,
dropconnect_dropout=0.0,
name="dense_dropconnect",
**kwargs):
if dropconnect_dropout != 0.0:
tf.logging.info("Applying dropconnect as ... | [
"Dense layer with dropconnect."
] |
Please provide a description of the function:def conv_relu_conv(inputs,
filter_size,
output_size,
first_kernel_size=3,
second_kernel_size=3,
padding="SAME",
nonpadding_mask=None,
dropout=... | [
"Hidden layer with RELU activation followed by linear projection.\n\n Args:\n inputs: A tensor.\n filter_size: An integer.\n output_size: An integer.\n first_kernel_size: An integer.\n second_kernel_size: An integer.\n padding: A string.\n nonpadding_mask: A tensor.\n dropout: A float.\n ... |
Please provide a description of the function:def sepconv_relu_sepconv(inputs,
filter_size,
output_size,
first_kernel_size=(1, 1),
second_kernel_size=(1, 1),
padding="LEFT",
... | [
"Hidden layer with RELU activation followed by linear projection."
] |
Please provide a description of the function:def conv_hidden_relu(inputs,
hidden_size,
output_size,
kernel_size=(1, 1),
second_kernel_size=(1, 1),
dropout=0.0,
**kwargs):
name = kwargs.pop(... | [
"Hidden layer with RELU activation followed by linear projection."
] |
Please provide a description of the function:def conv_gru(x,
kernel_size,
filters,
padding="SAME",
dilation_rate=(1, 1),
name=None,
reuse=None):
# Let's make a shorthand for conv call first.
def do_conv(args, name, bias_start, padding... | [
"Convolutional GRU in 1 dimension."
] |
Please provide a description of the function:def gru_feedfwd(a_t, h_prev, filters, name=None):
with tf.variable_scope(name, default_name="GRU", values=[a_t, h_prev]):
# we use right matrix multiplication to handle batches
# W_z and W_r have shape 2d, d. U_z U_r have shape d,d
z_t = (
tf.sigmoi... | [
"position-wise Feed-fwd GRU gates following the MPNN.\n\n Args:\n a_t: Tensor of shape [batch, length, depth] of current input\n h_prev: Tensor of shape [batch, length, depth] of prev input\n filters: an integer specifying number of dimensions of the filters\n name: A string\n Returns:\n h_t: [batc... |
Please provide a description of the function:def conv_lstm(x,
kernel_size,
filters,
padding="SAME",
dilation_rate=(1, 1),
name=None,
reuse=None):
with tf.variable_scope(
name, default_name="conv_lstm", values=[x], reuse=reuse... | [
"Convolutional LSTM in 1 dimension."
] |
Please provide a description of the function:def diagonal_conv_gru(x,
kernel_size,
filters,
dropout=0.0,
name=None,
reuse=None):
# Let's make a shorthand for conv call first.
def do_conv(args, name, bia... | [
"Diagonal Convolutional GRU as in https://arxiv.org/abs/1702.08727."
] |
Please provide a description of the function:def pad_to_same_length(x, y, final_length_divisible_by=1, axis=1):
if axis not in [1, 2]:
raise ValueError("Only axis=1 and axis=2 supported for now.")
with tf.name_scope("pad_to_same_length", values=[x, y]):
x_length = shape_list(x)[axis]
y_length = shape... | [
"Pad tensors x and y on axis 1 so that they have the same length."
] |
Please provide a description of the function:def pad_with_zeros(logits, labels):
with tf.name_scope("pad_with_zeros", values=[logits, labels]):
logits, labels = pad_to_same_length(logits, labels)
if len(labels.shape) == 3: # 2-d labels.
logits, labels = pad_to_same_length(logits, labels, axis=2)
... | [
"Pad labels on the length dimension to match logits length."
] |
Please provide a description of the function:def weights_prepend_inputs_to_targets(labels):
past_first_zero = tf.cumsum(to_float(tf.equal(labels, 0)), axis=1)
nonzero = to_float(labels)
return to_float(tf.not_equal(past_first_zero * nonzero, 0)) | [
"Assign weight 1.0 to only the \"targets\" portion of the labels.\n\n Weight 1.0 is assigned to all nonzero labels past the first zero.\n See prepend_mode in common_hparams.py\n\n Args:\n labels: A Tensor of int32s.\n\n Returns:\n A Tensor of floats.\n "
] |
Please provide a description of the function:def check_nonnegative(value):
if isinstance(value, tf.Tensor):
with tf.control_dependencies([tf.assert_greater_equal(value, 0)]):
value = tf.identity(value)
elif value < 0:
raise ValueError("Value must be non-negative.")
return value | [
"Check that the value is nonnegative."
] |
Please provide a description of the function:def weights_multi_problem(labels, taskid=-1):
taskid = check_nonnegative(taskid)
past_taskid = tf.cumsum(to_float(tf.equal(labels, taskid)), axis=1)
# Additionally zero out the task id location
past_taskid *= to_float(tf.not_equal(labels, taskid))
non_taskid = t... | [
"Assign weight 1.0 to only the \"targets\" portion of the labels.\n\n Weight 1.0 is assigned to all labels past the taskid.\n\n Args:\n labels: A Tensor of int32s.\n taskid: an int32 representing the task id for a problem.\n\n Returns:\n A Tensor of floats.\n\n Raises:\n ValueError: The Task ID must... |
Please provide a description of the function:def weights_multi_problem_all(labels, taskid=-1):
taskid = check_nonnegative(taskid)
weights = to_float(tf.not_equal(labels, 0))
past_taskid = tf.cumsum(to_float(tf.equal(labels, taskid)), axis=1)
# Additionally zero out the task id location
past_taskid *= to_fl... | [
"Assign weight 1.0 to only examples from the given task."
] |
Please provide a description of the function:def weights_multi_problem_input(labels, taskid=-1):
taskid = check_nonnegative(taskid)
weights_all_tokens = weights_multi_problem_all(labels, taskid)
weights_target = weights_multi_problem(labels, taskid)
return weights_all_tokens - weights_target | [
"Assign weight 1.0 to only the inputs for the given task."
] |
Please provide a description of the function:def weights_concatenated(labels):
eos_mask = tf.to_int32(tf.equal(labels, 1))
sentence_num = tf.cumsum(eos_mask, axis=1, exclusive=True)
in_target = tf.equal(tf.mod(sentence_num, 2), 1)
# first two tokens of each sentence are boilerplate.
sentence_num_plus_one =... | [
"Assign weight 1.0 to the \"target\" part of the concatenated labels.\n\n The labels look like:\n source English I love you . ID1 target French Je t'aime . ID1 source\n English the cat ID1 target French le chat ID1 source English ...\n\n We want to assign weight 1.0 to all words in the target text (includ... |
Please provide a description of the function:def padded_cross_entropy(logits,
labels,
label_smoothing,
weights_fn=weights_nonzero,
reduce_sum=True,
cutoff=0.0,
gaussian=F... | [
"Compute cross-entropy assuming 0s are padding.\n\n Computes a loss numerator (the sum of losses), and loss denominator\n (the number of non-padding tokens).\n\n Args:\n logits: a `Tensor` with shape `[batch, timesteps, vocab_size]`.\n optionally a FactoredTensor.\n labels: an integer `Tensor` with sh... |
Please provide a description of the function:def padded_cross_entropy_mixture(logits,
labels,
label_smoothing,
num_mixtures,
weights_fn=weights_nonzero,
re... | [
"Compute cross-entropy assuming 0s are padding.\n\n Computes a loss numerator (the sum of losses), and loss denominator\n (the number of non-padding tokens).\n\n Computes cross-entropy for each mixture, and returns the corresponding values\n for the mixture with the highest probability\n\n Args:\n logits: `... |
Please provide a description of the function:def dml_loss(pred, labels, weights_fn=_weights_one_third, reduce_sum=True):
real_labels = convert_rgb_to_symmetric_real(labels)
dml_loss_value = discretized_mix_logistic_loss(pred=pred, labels=real_labels)
weights = weights_fn(labels)
loss_num = weights * dml_loss... | [
"Discretized mixture of logistics loss.\n\n Args:\n pred: A [batch, height, width, num_mixtures*10] tensor of floats\n comprising one unconstrained mixture probability, three means\n (one per channel), three standard deviations (one per channel),\n and three coefficients which linearly parameteri... |
Please provide a description of the function:def split_to_discretized_mix_logistic_params(inputs):
batch, height, width, output_dim = shape_list(inputs) # pylint: disable=unbalanced-tuple-unpacking
num_mixtures = output_dim // 10
logits, locs, log_scales, coeffs = tf.split(
inputs,
num_or_size_spl... | [
"Splits input tensor into parameters of discretized mixture logistic.\n\n Args:\n inputs: A [batch, height, width, num_mixtures*10] tensor of floats\n comprising one unconstrained mixture probability, three means\n (one per channel), three standard deviations (one per channel),\n and three coeffi... |
Please provide a description of the function:def discretized_mix_logistic_loss(pred, labels):
logits, locs, log_scales, coeffs = split_to_discretized_mix_logistic_params(
pred)
# Tile labels to broadcast compute across the mixture dimension.
batch, height, width, num_mixtures = shape_list(logits) # py... | [
"Computes negative log probability for the discretized mixture of logistics.\n\n The distribution of a whole pixel is a mixture of 3-dimensional discretized\n logistic distributions. The 3-D discretized logistic factorizes as 3 1-D\n discretized logistic distributions, one for each channel. It defines\n\n ```no... |
Please provide a description of the function:def sample_from_discretized_mix_logistic(pred, seed=None):
logits, locs, log_scales, coeffs = split_to_discretized_mix_logistic_params(
pred)
# Sample mixture indicator given logits using the gumbel max trick.
num_mixtures = shape_list(logits)[-1]
gumbel_n... | [
"Sampling from a discretized mixture of logistics.\n\n Args:\n pred: A [batch, height, width, num_mixtures*10] tensor of floats\n comprising one unconstrained mixture probability, three means\n (one per channel), three standard deviations (one per channel),\n and three coefficients which linearly... |
Please provide a description of the function:def smoothing_cross_entropy(logits,
labels,
vocab_size,
confidence,
gaussian=False):
with tf.name_scope("smoothing_cross_entropy", values=[logits, labels]):
... | [
"Cross entropy with label smoothing to limit over-confidence.\n\n Args:\n logits: Tensor of shape [batch_size, ?, ?, ?, vocab_size].\n labels: Tensor of shape [batch_size, ?, ?, ?].\n vocab_size: Tensor representing the size of the vocabulary.\n confidence: Used to determine on and off values for label... |
Please provide a description of the function:def global_pool_1d(inputs, pooling_type="MAX", mask=None):
with tf.name_scope("global_pool", values=[inputs]):
if mask is not None:
mask = tf.expand_dims(mask, axis=2)
inputs = tf.multiply(inputs, mask)
if pooling_type == "MAX":
# A tf.pool ca... | [
"Pool elements across the last dimension.\n\n Useful to convert a list of vectors into a single vector so as\n to get a representation of a set.\n\n Args:\n inputs: A tensor of shape [batch_size, sequence_length, input_dims]\n containing the sequences of input vectors.\n pooling_type: the pooling type... |
Please provide a description of the function:def running_global_pool_1d(inputs, pooling_type="MAX"):
del pooling_type
with tf.name_scope("running_global_pool", values=[inputs]):
scan_fct = tf.maximum
# Permute inputs so seq_length is first.
elems = tf.transpose(inputs, [1, 0, 2])
# Perform scan.
... | [
"Same global pool, but only for the elements up to the current element.\n\n Useful for outputs where the state of future elements is not known.\n Takes no mask as all elements up to the current element are assumed to exist.\n Currently only supports maximum. Equivalent to using a lower triangle bias.\n\n Args:\... |
Please provide a description of the function:def gated_linear_unit_layer(x, name=None):
with tf.variable_scope(name, default_name="glu_layer", values=[x]):
depth = shape_list(x)[-1]
x = layers().Dense(depth * 2, activation=None)(x)
x, gating_x = tf.split(x, 2, axis=-1)
return x * tf.nn.sigmoid(gati... | [
"Gated linear unit layer.\n\n Paper: Language Modeling with Gated Convolutional Networks.\n Link: https://arxiv.org/abs/1612.08083\n x = Wx * sigmoid(W'x).\n\n Args:\n x: A tensor\n name: A string\n\n Returns:\n A tensor of the same shape as x.\n "
] |
Please provide a description of the function:def sru_with_scan(x,
num_layers=2,
activation=None,
initial_state=None,
name=None,
reuse=None):
if num_layers < 1:
raise ValueError("Number of layers must be positive: %d" % nu... | [
"SRU cell as in https://arxiv.org/abs/1709.02755.\n\n This implementation uses tf.scan and can incur overhead, see the full SRU\n function doc for details and an implementation that is sometimes faster.\n\n Args:\n x: A tensor of shape [batch, ..., channels] ; ... is treated as time.\n num_layers: How many... |
Please provide a description of the function:def sru(x,
num_layers=2,
activation=None,
initial_state=None,
name=None,
reuse=None):
if num_layers < 1:
raise ValueError("Number of layers must be positive: %d" % num_layers)
if is_xla_compiled(): # On TPU the XLA does a g... | [
"SRU cell as in https://arxiv.org/abs/1709.02755.\n\n As defined in the paper:\n (1) x'_t = W x_t\n (2) f_t = sigmoid(Wf x_t + bf)\n (3) r_t = sigmoid(Wr x_t + br)\n (4) c_t = f_t * c_{t-1} + (1 - f_t) * x'_t\n (5) h_t = r_t * activation(c_t) + (1 - r_t) * x_t\n\n This version uses functional ops to be faste... |
Please provide a description of the function:def linear_set_layer(layer_size,
inputs,
context=None,
activation_fn=tf.nn.relu,
dropout=0.0,
name=None):
with tf.variable_scope(
name, default_name="linear_se... | [
"Basic layer type for doing funky things with sets.\n\n Applies a linear transformation to each element in the input set.\n If a context is supplied, it is concatenated with the inputs.\n e.g. One can use global_pool_1d to get a representation of the set which\n can then be used as the context for the next ... |
Please provide a description of the function:def ravanbakhsh_set_layer(layer_size,
inputs,
mask=None,
sequential=False,
activation_fn=tf.nn.tanh,
dropout=0.0,
name=... | [
"Layer from Deep Sets paper: https://arxiv.org/abs/1611.04500 .\n\n More parameter-efficient version of a linear-set-layer with context.\n\n Args:\n layer_size: Dimension to transform the input vectors to.\n inputs: A tensor of shape [batch_size, sequence_length, vector]\n containing the sequences of i... |
Please provide a description of the function:def fn_device_dependency_dict():
default_graph = tf.get_default_graph()
if not hasattr(default_graph, "dependency_dict"):
default_graph.dependency_dict = collections.defaultdict(list)
return default_graph.dependency_dict | [
"State container for fn_device_dependency."
] |
Please provide a description of the function:def fn_device_dependency(name, device=""):
key = name + "_" + device
outs = []
def body():
with tf.control_dependencies(fn_device_dependency_dict()[key]):
yield outs
assert outs
deps = outs
if isinstance(outs[0], (list, tuple)):
... | [
"Add control deps for name and device."
] |
Please provide a description of the function:def underlying_variable_ref(t):
while t.op.type in ["Identity", "ReadVariableOp", "Enter"]:
t = t.op.inputs[0]
op_type = t.op.type
if "Variable" in op_type or "VarHandle" in op_type:
return t
else:
return None | [
"Find the underlying variable ref.\n\n Traverses through Identity, ReadVariableOp, and Enter ops.\n Stops when op type has Variable or VarHandle in name.\n\n Args:\n t: a Tensor\n\n Returns:\n a Tensor that is a variable ref, or None on error.\n "
] |
Please provide a description of the function:def underlying_variable(t):
t = underlying_variable_ref(t)
assert t is not None
# make sure that the graph has a variable index and that it is up-to-date
if not hasattr(tf.get_default_graph(), "var_index"):
tf.get_default_graph().var_index = {}
var_index = t... | [
"Find the underlying tf.Variable object.\n\n Args:\n t: a Tensor\n\n Returns:\n tf.Variable.\n "
] |
Please provide a description of the function:def approximate_split(x, num_splits, axis=0):
size = shape_list(x)[axis]
size_splits = [tf.div(size + i, num_splits) for i in range(num_splits)]
return tf.split(x, size_splits, axis=axis) | [
"Split approximately equally into num_splits parts.\n\n Args:\n x: a Tensor\n num_splits: an integer\n axis: an integer.\n\n Returns:\n a list of num_splits Tensors.\n "
] |
Please provide a description of the function:def smoothing_cross_entropy_factored_grad(op, dy):
a = op.inputs[0]
b = op.inputs[1]
labels = op.inputs[2]
confidence = op.inputs[3]
num_splits = 16
vocab_size = shape_list(b)[0]
labels = approximate_split(labels, num_splits)
a = approximate_split(a, num_s... | [
"Gradient function for smoothing_cross_entropy_factored."
] |
Please provide a description of the function:def smoothing_cross_entropy_factored(a, b, labels, confidence):
num_splits = 16
vocab_size = shape_list(b)[0]
labels = approximate_split(labels, num_splits)
a = approximate_split(a, num_splits)
parts = []
for part in range(num_splits):
with tf.control_depe... | [
"Memory-efficient computation of smoothing cross-entropy.\n\n Avoids realizing the entire logits matrix at once.\n\n Args:\n a: a Tensor with shape [batch, inner_dim]\n b: a Tensor with shape [vocab_size, inner_dim]\n labels: an integer Tensor with shape [batch]\n confidence: a float\n\n Returns:\n ... |
Please provide a description of the function:def padded_cross_entropy_factored(factored_logits,
labels,
label_smoothing,
weights_fn=weights_nonzero,
reduce_sum=True):
a = factored... | [
"Memory-efficient computation of smoothing cross-entropy.\n\n Avoids realizing the entire logits matrix at once.\n\n Args:\n factored_logits: a `FactoredTensor` representing a Tensor\n with shape `[batch, timesteps, vocab_size]`.\n labels: an integer `Tensor` with shape `[batch, timesteps]`.\n labe... |
Please provide a description of the function:def fn_with_custom_grad(grad_fn, use_global_vars=False):
def dec(fn):
@functools.wraps(fn)
def wrapped(*args):
return _fn_with_custom_grad(
fn, args, grad_fn, use_global_vars=use_global_vars)
return wrapped
return dec | [
"Decorator to create a subgraph with a custom gradient function.\n\n The subgraph created by the decorated function is NOT put in a Defun and so\n does not suffer from the limitations of the Defun (all subgraph ops on the\n same device, no summaries).\n\n Args:\n grad_fn: function with signature\n (inpu... |
Please provide a description of the function:def _fn_with_custom_grad(fn, inputs, grad_fn, use_global_vars=False):
vs = tf.get_variable_scope()
get_vars_fn = (
vs.global_variables if use_global_vars else vs.trainable_variables)
len_before_vars = len(get_vars_fn())
inputs = list(inputs)
outputs = fn(*... | [
"Create a subgraph with a custom gradient.\n\n Args:\n fn: function that takes inputs as arguments and produces 1 or more Tensors.\n inputs: list<Tensor>, will be passed as fn(*inputs).\n grad_fn: function with signature\n (inputs, vars, outputs, output_grads) -> (grad_inputs, grad_vars),\n all ... |
Please provide a description of the function:def conv_hidden_relu_memory_efficient(x,
filter_size,
epsilon=1e-6,
forget=True,
test_vars=None,
... | [
"LayerNorm, Conv, ReLU, Conv.\n\n All convolutions have kernel size 1.\n\n returns conv(relu(conv(layer_norm(x))))\n\n Args:\n x: input Tensor with shape [batch, length, io_size]\n filter_size: an integer - size of the hidden layer.\n epsilon: a float (for layer norm)\n forget: a boolean - forget for... |
Please provide a description of the function:def shape_list(x):
x = tf.convert_to_tensor(x)
# If unknown rank, return dynamic shape
if x.get_shape().dims is None:
return tf.shape(x)
static = x.get_shape().as_list()
shape = tf.shape(x)
ret = []
for i, dim in enumerate(static):
if dim is None:... | [
"Return list of dims, statically where possible."
] |
Please provide a description of the function:def sample_with_temperature(logits, temperature, sampling_keep_top_k=-1):
if temperature == 0.0:
# TF argmax doesn't handle >5 dimensions, so we reshape here.
logits_shape = shape_list(logits)
argmax = tf.argmax(tf.reshape(logits, [-1, logits_shape[-1]]), ax... | [
"Either argmax or random sampling.\n\n Args:\n logits: a Tensor.\n temperature: a float 0.0=argmax 1.0=random\n sampling_keep_top_k: If not -1, only sample from the top k logits.\n Returns:\n a Tensor with one fewer dimension than logits.\n "
] |
Please provide a description of the function:def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]):
# Needed info is constant, so we construct in numpy
if num_lower < 0:
num_lower = rows - 1
if num_u... | [
"Matrix band part of ones.\n\n Args:\n rows: int determining number of rows in output\n cols: int\n num_lower: int, maximum distance backward. Negative values indicate\n unlimited.\n num_upper: int, maximum distance forward. Negative values indicate\n unlimited.\n out_shape: shape to resha... |
Please provide a description of the function:def reshape_like_all_dims(a, b):
ret = tf.reshape(a, tf.shape(b))
if not tf.executing_eagerly():
ret.set_shape(b.get_shape())
return ret | [
"Reshapes a to match the shape of b."
] |
Please provide a description of the function:def recompute_grad(fn):
@functools.wraps(fn)
def wrapped(*args):
return _recompute_grad(fn, args)
return wrapped | [
"Decorator that recomputes the function on the backwards pass.\n\n Args:\n fn: a function that takes Tensors (all as positional arguments) and returns\n a tuple of Tensors.\n\n Returns:\n A wrapped fn that is identical to fn when called, but its activations will\n be discarded and recomputed on the ... |
Please provide a description of the function:def _recompute_grad(fn, args):
cached_vs = []
cached_arg_scope = []
def grad_fn(inputs, variables, outputs, output_grads):
del outputs
variables = [underlying_variable_ref(v) for v in variables]
# Recompute outputs
with tf.control_dependencies... | [
"See recompute_grad.",
"Recompute outputs for gradient computation."
] |
Please provide a description of the function:def dense(x, units, **kwargs):
layer_collection = kwargs.pop("layer_collection", None)
activations = layers().Dense(units, **kwargs)(x)
if layer_collection:
# We need to find the layer parameters using scope name for the layer, so
# check that the layer is n... | [
"Identical to layers.dense."
] |
Please provide a description of the function:def batch_dense(inputs,
units,
activation=None,
kernel_initializer=None,
reuse=None,
name=None):
inputs_shape = shape_list(inputs)
if len(inputs_shape) != 3:
raise ValueError("inputs m... | [
"Multiply a batch of input matrices by a batch of parameter matrices.\n\n Each input matrix is multiplied by the corresponding parameter matrix.\n\n This is useful in a mixture-of-experts where the batch represents different\n experts with different inputs.\n\n Args:\n inputs: a Tensor with shape [batch, len... |
Please provide a description of the function:def mix(x1,
x2,
steps,
is_training,
min_prob=0.0,
max_prob=1.0,
mode="lin",
simple=False,
broadcast_last=False):
with tf.name_scope("mix"):
if not is_training:
if max_prob >= 1.0:
return x... | [
"Mix starting with x2, mixing mixing, going towards x1.",
"Create the result.\n\n Separate function to speed it up later (see below).\n\n Returns:\n Tensor of mixed inputs.\n "
] |
Please provide a description of the function:def brelu(x):
x_shape = shape_list(x)
x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
y1 = tf.nn.relu(x1)
y2 = -tf.nn.relu(-x2)
return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape) | [
"Bipolar ReLU as in https://arxiv.org/abs/1709.04054."
] |
Please provide a description of the function:def belu(x):
x_shape = shape_list(x)
x1, x2 = tf.split(tf.reshape(x, x_shape[:-1] + [-1, 2]), 2, axis=-1)
y1 = tf.nn.elu(x1)
y2 = -tf.nn.elu(-x2)
return tf.reshape(tf.concat([y1, y2], axis=-1), x_shape) | [
"Bipolar ELU as in https://arxiv.org/abs/1709.04054."
] |
Please provide a description of the function:def gelu(x):
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
return x * cdf | [
"Gaussian Error Linear Unit.\n\n This is a smoother version of the RELU.\n Original paper: https://arxiv.org/abs/1606.08415\n\n Args:\n x: float Tensor to perform activation.\n\n Returns:\n x with the GELU activation applied.\n "
] |
Please provide a description of the function:def nac(x, depth, name=None, reuse=None):
with tf.variable_scope(name, default_name="nac", values=[x], reuse=reuse):
x_shape = shape_list(x)
w = tf.get_variable("w", [x_shape[-1], depth])
m = tf.get_variable("m", [x_shape[-1], depth])
w = tf.tanh(w) * tf... | [
"NAC as in https://arxiv.org/abs/1808.00508."
] |
Please provide a description of the function:def nalu(x, depth, epsilon=1e-30, name=None, reuse=None):
with tf.variable_scope(name, default_name="nalu", values=[x], reuse=reuse):
x_shape = shape_list(x)
x_flat = tf.reshape(x, [-1, x_shape[-1]])
gw = tf.get_variable("w", [x_shape[-1], depth])
g = tf... | [
"NALU as in https://arxiv.org/abs/1808.00508."
] |
Please provide a description of the function:def argmax_with_score(logits, axis=None):
axis = axis or len(logits.get_shape()) - 1
predictions = tf.argmax(logits, axis=axis)
logits_shape = shape_list(logits)
prefix_shape, vocab_size = logits_shape[:-1], logits_shape[-1]
prefix_size = 1
for d in prefix_sh... | [
"Argmax along with the value."
] |
Please provide a description of the function:def top_kth_iterative(x, k):
# The iterative computation is as follows:
#
# cur_x = x
# for _ in range(k):
# top_x = maximum of elements of cur_x on the last axis
# cur_x = cur_x where cur_x < top_x and 0 everywhere else (top elements)
#
# We encode th... | [
"Compute the k-th top element of x on the last axis iteratively.\n\n This assumes values in x are non-negative, rescale if needed.\n It is often faster than tf.nn.top_k for small k, especially if k < 30.\n Note: this does not support back-propagation, it stops gradients!\n\n Args:\n x: a Tensor of non-negati... |
Please provide a description of the function:def top_1_tpu(inputs):
inputs_max = tf.reduce_max(inputs, axis=-1, keepdims=True)
mask = tf.to_int32(tf.equal(inputs_max, inputs))
index = tf.range(tf.shape(inputs)[-1]) * mask
return tf.squeeze(inputs_max, -1), tf.reduce_max(index, axis=-1) | [
"find max and argmax over the last dimension.\n\n Works well on TPU\n\n Args:\n inputs: A tensor with shape [..., depth]\n\n Returns:\n values: a Tensor with shape [...]\n indices: a Tensor with shape [...]\n "
] |
Please provide a description of the function:def index_last_dim_with_indices(x, indices):
assert len(x.shape) == len(indices.shape) + 1
x_shape = shape_list(x)
vocab_size = x_shape[-1]
flat_x = tf.reshape(x, [list_product(x_shape[:-1]), vocab_size])
flat_indices = tf.reshape(indices, [list_product(x_shap... | [
"Use indices to index into the last axis of x.\n\n This can be useful for recovering the actual probabilities of a sample from a\n probability distribution.\n\n Args:\n x: Tensor, n-d.\n indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1)\n dimensions of x. The values of indices ... |
Please provide a description of the function:def should_generate_summaries():
name_scope = tf.contrib.framework.get_name_scope()
if name_scope and "while/" in name_scope:
# Summaries don't work well within tf.while_loop()
return False
if tf.get_variable_scope().reuse:
# Avoid generating separate su... | [
"Is this an appropriate context to generate summaries.\n\n Returns:\n a boolean\n "
] |
Please provide a description of the function:def reshape_like(a, b):
ret = tf.reshape(a, tf.concat([tf.shape(b)[:-1], tf.shape(a)[-1:]], 0))
if not tf.executing_eagerly():
ret.set_shape(b.get_shape().as_list()[:-1] + a.get_shape().as_list()[-1:])
return ret | [
"Reshapes a to match the shape of b in all but the last dimension."
] |
Please provide a description of the function:def summarize_video(video, prefix, max_outputs=1):
video_shape = shape_list(video)
if len(video_shape) != 5:
raise ValueError("Assuming videos given as tensors in the format "
"[batch, time, height, width, channels] but got one "
... | [
"Summarize the video using image summaries starting with prefix."
] |
Please provide a description of the function:def cast_like(x, y):
x = tf.convert_to_tensor(x)
y = tf.convert_to_tensor(y)
if x.dtype.base_dtype == y.dtype.base_dtype:
return x
cast_x = tf.cast(x, y.dtype)
if cast_x.device != x.device:
x_name = "(eager Tensor)"
try:
x_name = x.name
e... | [
"Cast x to y's dtype, if necessary."
] |
Please provide a description of the function:def make_even_size(x):
x_shape = x.get_shape().as_list()
assert len(x_shape) > 2, "Only 3+-dimensional tensors supported."
shape = [dim if dim is not None else -1 for dim in x_shape]
new_shape = x_shape # To make sure constant shapes remain constant.
if x_shape... | [
"Pad x to be even-sized on axis 1 and 2, but only if necessary."
] |
Please provide a description of the function:def sliced_gan_loss(input1,
input2,
discriminator,
num_vecs,
do_random_vecs=True,
do_tanh=True,
return_logits=False):
with tf.variable_scope("sliced_g... | [
"Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947.\n\n Puts input1 and input2 through the provided discriminator to get logits.\n Then, computes num_vecs random projections of the logits, sorts them on\n the batch dimension and returns the L2 loss between the sorted vectors.\n See the ab... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.