Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_title(page): start_pos = page.find("<title>") end_pos = page.find("</title>") assert start_pos != -1 assert end_pos != -1 start_pos += len("<title>") return text_encoder.to_unicode_utf8(page[start_pos:end_pos])
[ "Extract the title from a page.\n\n Args:\n page: a string\n Returns:\n a string\n " ]
Please provide a description of the function:def get_id(page): start_pos = page.find("<id>") end_pos = page.find("</id>") assert start_pos != -1 assert end_pos != -1 start_pos += len("<id>") return int(page[start_pos:end_pos])
[ "Extract the id from a page.\n\n Args:\n page: a string\n Returns:\n an integer\n " ]
Please provide a description of the function:def get_revisions(page): start_string = " <revision>\n" end_string = " </revision>\n" ret = [] current_pos = 0 while True: start_pos = page.find(start_string, current_pos) if start_pos == -1: break end_pos = page.find(end_string, start_po...
[ "Extract the revisions of a page.\n\n Args:\n page: a string\n Returns:\n a list of strings\n " ]
Please provide a description of the function:def parse_page(raw_page): ret = {"title": get_title(raw_page), "id": get_id(raw_page)} if ":" in ret["title"]: return None ret["revisions"] = get_revisions(raw_page) return ret
[ "Create a dictionary with title, id, and list of revisions.\n\n The dictionary contains:\n \"title\": a string\n \"id\": an integer\n \"revisions\": a list of strings\n\n Args:\n raw_page: a string\n\n Returns:\n a dictionary, or None in the case of an error.\n " ]
Please provide a description of the function:def maybe_copy_file_to_directory(source_filepath, target_directory): if not tf.gfile.Exists(target_directory): tf.logging.info("Creating directory %s" % target_directory) os.mkdir(target_directory) target_filepath = os.path.join(target_directory, ...
[ "Copy a file to a directory if it is not already there.\n\n Returns the target filepath.\n\n Args:\n source_filepath: a string\n target_directory: a string\n\n Returns:\n a string\n " ]
Please provide a description of the function:def corpus_page_generator(corpus_files, tmp_dir, max_page_size_exp): for remote_filepath in corpus_files: filepath = maybe_copy_file_to_directory(remote_filepath, tmp_dir) tf.logging.info("Reading from " + filepath) command = ["7z", "x", "-so", filepath] ...
[ "Generate pages from a list of .7z encoded history dumps.\n\n Args:\n corpus_files: a list of strings\n tmp_dir: a string\n max_page_size_exp: an integer\n\n Yields:\n strings\n " ]
Please provide a description of the function:def get_text(revision, strip=True): # text start tag looks like "<text ..otherstuff>" start_pos = revision.find("<text") assert start_pos != -1 end_tag_pos = revision.find(">", start_pos) assert end_tag_pos != -1 end_tag_pos += len(">") end_pos = revision.fi...
[ "Extract the text from a revision.\n\n Args:\n revision: a string\n strip: a boolean\n\n Returns:\n a string\n " ]
Please provide a description of the function:def _remove_curly_braces(text): current_pos = 0 depth = 0 ret = "" for match in re.finditer("[{}]", text): if depth == 0: ret += text[current_pos:match.start()] depth += 1 if text[match.start()] == "{" else -1 current_pos = match.end() if depth...
[ "Remove everything in curly braces.\n\n Curly braces may be nested, so we keep track of depth.\n\n Args:\n text: a string\n Returns:\n a string\n " ]
Please provide a description of the function:def _remove_double_brackets(text): def replacement_fn(s): if ":" in s: # this is probably a category or something like that. return "" # keep the part after the bar. bar_pos = s.find("|") if bar_pos == -1: return s return s[bar_pos...
[ "Remove double brackets, but leave the viewable text.\n\n Args:\n text: a string\n Returns:\n a string\n " ]
Please provide a description of the function:def _remove_boring_lines(text): lines = text.split("\n") filtered = [line for line in lines if re.match("[a-zA-z\"\']", line)] return "\n".join(filtered)
[ "Remove lines that do not start with a letter or a quote.\n\n From inspecting the data, this seems to leave in most prose and remove\n most weird stuff.\n\n Args:\n text: a string\n Returns:\n a string\n " ]
Please provide a description of the function:def get_or_generate_vocabulary(data_dir, tmp_dir, data_prefix, max_page_size_exp, approx_vocab_size=32768, strip=True): ...
[ "Get or generate the vocabulary.\n\n Args:\n data_dir: a string\n tmp_dir: a string\n data_prefix: a string\n max_page_size_exp: an integer\n approx_vocab_size: an integer\n strip: a boolean\n\n Returns:\n a TextEncoder\n ", "Line generator for vocab." ]
Please provide a description of the function:def get_encoder_from_vocab(vocab_filepath): if not tf.gfile.Exists(vocab_filepath): raise ValueError("Vocab file does not exist: {}.".format(vocab_filepath)) tf.logging.info("Found vocab file: %s", vocab_filepath) encoder = text_encoder.SubwordTextEncoder(vocab...
[ "Get encoder from vocab file.\n\n If vocab is not found in output dir, it will be copied there by\n copy_vocab_to_output_dir to clarify the vocab used to generate the data.\n\n Args:\n vocab_filepath: path to vocab, either local or cns\n\n Returns:\n A SubwordTextEncoder vocabulary object. None if the out...
Please provide a description of the function:def edit_distance_filter(source_target_input, max_equal_to_diff_ratio=0): thrown_out_count = 0 source_target_output = [] if not max_equal_to_diff_ratio: return source_target_input, thrown_out_count for src_tgt in source_target_input: opcodes = fast_match...
[ "Filter out examples that exceed max_edit_ratio between source and target.\n\n Args:\n source_target_input: a list of [source, target] pairs\n max_equal_to_diff_ratio: cutoff for ratio of equal chars / diff chars\n between source and target\n\n Returns:\n source_target_output: filtered subset...
Please provide a description of the function:def introduce_errors(s, corruption_rate=3e-3, infill_marker="|?|", max_infill_len=8): num_errors = 0 ret = [] operations = [ "delete", # delete a character "insert", # insert a random chara...
[ "Artificially add spelling errors and infill markers.\n\n This function should be applied to the inputs of a correction model.\n\n The artificial errors are particularly useful to train a network to\n correct spelling when the training data does not contain many\n natural errors.\n\n Also replaces some substri...
Please provide a description of the function:def fast_match_sequences(a, b, a_start=0, a_end=None, b_start=0, b_end=None, min_match_length=3, max...
[ "Compute diffs between two sequences.\n\n This function is similar in functionality and spirit to\n difflib.SequenceMatcher.get_opcodes, but it seems to run faster.\n\n if a_start, a_end, b_start, b_end are specified, then we compute diffs of\n the segments a[a_start:a_end] and b[b_start:b_end]. Returned indic...
Please provide a description of the function:def begin(self): variables_to_restore = tf.contrib.framework.get_variables_to_restore( include=self._include, exclude=self._exclude) # remove new_model_scope from variable name prefix assignment_map = {variable.name[len(self._new_model_scope):]: vari...
[ "Load variables from checkpoint.\n\n New model variables have the following name foramt:\n new_model_scope/old_model_scope/xxx/xxx:0 To find the map of\n name to variable, need to strip the new_model_scope and then\n match the old_model_scope and remove the suffix :0.\n\n " ]
Please provide a description of the function:def create_time_step(cls, observation=None, done=False, raw_reward=None, processed_reward=None, action=None): return cls(observation, done, raw_reward...
[ "Creates a TimeStep with both rewards and actions as optional." ]
Please provide a description of the function:def attention(targets_shifted, inputs_encoded, norm_fn, hparams, bias=None): separabilities = [hparams.separability, hparams.separability] if hparams.separability < 0: separabilities = [hparams.separability - 1, hparams.separability] targets_timed = common_layer...
[ "Complete attention layer with preprocessing." ]
Please provide a description of the function:def multi_conv_res(x, padding, name, layers, hparams, mask=None, source=None): with tf.variable_scope(name): padding_bias = None if mask is not None: padding_bias = (1.0 - mask) * -1e9 # Bias to not attend to padding. if padding == "LEFT": # Do not...
[ "A stack of separable convolution blocks with residual connections." ]
Please provide a description of the function:def rank_loss(sentence_emb, image_emb, margin=0.2): with tf.name_scope("rank_loss"): # Normalize first as this is assumed in cosine similarity later. sentence_emb = tf.nn.l2_normalize(sentence_emb, 1) image_emb = tf.nn.l2_normalize(image_emb, 1) # Both s...
[ "Experimental rank loss, thanks to kkurach@ for the code." ]
Please provide a description of the function:def similarity_cost(inputs_encoded, targets_encoded): # This is a first very simple version: handle variable-length by padding # to same length and putting everything into batch. In need of a better way. x, y = common_layers.pad_to_same_length(inputs_encoded, target...
[ "Loss telling to be more similar to your own targets than to others." ]
Please provide a description of the function:def slicenet_middle(inputs_encoded, targets, target_space_emb, mask, hparams): def norm_fn(x, name): with tf.variable_scope(name, default_name="norm"): return common_layers.apply_norm(x, hparams.norm_type, hparams.hidden_size, ...
[ "Middle part of slicenet, connecting encoder and decoder." ]
Please provide a description of the function:def embedding_to_padding(emb): emb_sum = tf.reduce_sum(tf.abs(emb), axis=-1, keep_dims=True) return tf.to_float(tf.equal(emb_sum, 0.0))
[ "Input embeddings -> is_padding." ]
Please provide a description of the function:def slicenet_internal(inputs, targets, target_space, hparams, run_decoder=True): with tf.variable_scope("slicenet"): # Project to hidden size if necessary if inputs.get_shape().as_list()[-1] != hparams.hidden_size: inputs = common_layers.conv_block( ...
[ "The slicenet model, main step used for training." ]
Please provide a description of the function:def slicenet_params1(): hparams = common_hparams.basic_params1() hparams.batch_size = 1024 hparams.hidden_size = 768 hparams.dropout = 0.5 hparams.symbol_dropout = 0.2 hparams.label_smoothing = 0.1 hparams.clip_grad_norm = 2.0 hparams.num_hidden_layers = 4...
[ "Set of hyperparameters." ]
Please provide a description of the function:def slicenet_params1_noam(): hparams = slicenet_params1() hparams.learning_rate_decay_scheme = "noam" hparams.learning_rate = 1.0 hparams.learning_rate_warmup_steps = 4000 hparams.initializer = "uniform_unit_scaling" hparams.optimizer_adam_epsilon = 1e-9 hpa...
[ "Version with Noam's decay scheme." ]
Please provide a description of the function:def slicenet_params1_tiny(): hparams = slicenet_params1() hparams.attention_type = "simple" hparams.separability = 0 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.batch_size = 512 hparams.learning_rate_warmup_steps = 200 return hparams
[ "Version for fast local runs." ]
Please provide a description of the function:def slicenet_range1(ranged_hparams): rhp = ranged_hparams rhp.set_float("clip_grad_norm", 1.0, 10.0, scale=rhp.LOG_SCALE) rhp.set_float("learning_rate", 0.02, 1.0, scale=rhp.LOG_SCALE) rhp.set_float("optimizer_adam_beta2", 0.995, 0.998) rhp.set_float("weight_dec...
[ "Small range of hyperparameters." ]
Please provide a description of the function:def encode(self, s): sentence = s tokens = sentence.strip().split() ids = [] ids_extend = [] oovs = {} for t in tokens: if t in self._token_to_id: ids.append(self._token_to_id[t]) ids_extend.append(self._token_to_id[t]) ...
[ "Converts a space-separated string of tokens to lists of ids.\n\n Also store temporary vocabulary IDs for source OOV tokens. OOVs are\n represented by their temporary OOV number. E.g., if the vocabulary size\n is 50k and the source has 3 OOVs, then these temporary OOV numbers will\n be 50000, 50001, 500...
Please provide a description of the function:def encode_target(self, target, source_oovs): tokens = target.strip().split() ids = [] ids_extend = [] for t in tokens: if t in self._token_to_id: i = self._token_to_id[t] ids.append(i) ids_extend.append(i) else: ...
[ "Converts a space-separated string of tokens to lists of ids.\n\n Also store a version of extened vocabulary IDs.\n For target OOVs that are in the source, encode them using the temporary\n vocab IDs.\n For target OOVs not in the source, encode them as <UNK>\n\n Args:\n target: target string\n ...
Please provide a description of the function:def decode_list_oov(self, ids, source_oov_id_to_token): seq = reversed(ids) if self._reverse else ids tokens = [] for cur_id in seq: if cur_id in self._id_to_token: tokens.append(self._id_to_token[cur_id]) else: tokens.append(sour...
[ "decode ids back to tokens, considering OOVs temporary IDs.\n\n Args:\n ids: vocab ids. Could possibly include source temporary OOV ID starting\n from vocab_size.\n source_oov_id_to_token: a list of source OOV tokens, with the order the\n same as they appear in the source.\n\n Returns:\n ...
Please provide a description of the function:def _smallest_size_at_least(height, width, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) height = tf.to_float(height) width = tf.to_float(width) smallest_side = tf.to_float(smallest_side) scale = tf.cond( tf.greater(...
[ "Computes new shape with the smallest side equal to `smallest_side`.\n\n Computes new shape with the smallest side equal to `smallest_side` while\n preserving the original aspect ratio.\n\n Args:\n height: an int32 scalar tensor indicating the current height.\n width: an int32 scalar tensor indicating ...
Please provide a description of the function:def _aspect_preserving_resize(image, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) shape = tf.shape(image) height = shape[0] width = shape[1] new_height, new_width = _smallest_size_at_least(height, width, smallest_side) i...
[ "Resize images preserving the original aspect ratio.\n\n Args:\n image: A 3-D image `Tensor`.\n smallest_side: A python integer or scalar `Tensor` indicating the size of\n the smallest side after resize.\n\n Returns:\n resized_image: A 3-D tensor containing the resized image.\n " ]
Please provide a description of the function:def _distort_color(image, color_ordering=0, scope=None): with tf.name_scope(scope, "distort_color", [image]): if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upp...
[ "Distort the color of a Tensor image.\n\n Each color distortion is non-commutative and thus ordering of the color ops\n matters. Ideally we would randomly permute the ordering of the color ops.\n Rather then adding that level of complication, we select a distinct ordering\n of color ops for each preprocessing t...
Please provide a description of the function:def _apply_with_random_selector(x, func, num_cases): sel = tf.random_uniform([], maxval=num_cases, dtype=tf.int32) # Pass the real x only to one of the func calls. return control_flow_ops.merge([ func(control_flow_ops.switch(x, tf.equal(sel, case))[1], case) ...
[ "Computes func(x, sel), with sel sampled from [0...num_cases-1].\n\n Args:\n x: input Tensor.\n func: Python function to apply.\n num_cases: Python int32, number of cases to sample sel from.\n\n Returns:\n The result of func(x, sel), where func receives the value of the\n selector as a python integ...
Please provide a description of the function:def _mean_image_subtraction(image, means): if image.get_shape().ndims != 3: raise ValueError("Input must be of size [height, width, C>0]") num_channels = image.get_shape().as_list()[-1] if len(means) != num_channels: raise ValueError("len(means) must match t...
[ "Subtracts the given means from each image channel.\n\n For example:\n means = [123.68, 116.779, 103.939]\n image = _mean_image_subtraction(image, means)\n\n Note that the rank of `image` must be known.\n\n Args:\n image: a tensor of size [height, width, C].\n means: a C-vector of values to subtract ...
Please provide a description of the function:def vqa_v2_preprocess_image( image, height, width, mode, resize_side=512, distort=True, image_model_fn="resnet_v1_152", ): image = tf.image.convert_image_dtype(image, dtype=tf.float32) assert resize_side > 0 if resize_side: image = _...
[ "vqa v2 preprocess image." ]
Please provide a description of the function:def transformer_prepare_encoder(inputs, target_space, hparams, features=None): ishape_static = inputs.shape.as_list() encoder_input = inputs if features and "inputs_segmentation" in features: # Packed dataset. Keep the examples from seeing each other. input...
[ "Prepare one shard of the model for the encoder.\n\n Args:\n inputs: a Tensor.\n target_space: a Tensor.\n hparams: run hyperparameters\n features: optionally pass the entire features dictionary as well.\n This is needed now for \"packed\" datasets.\n\n Returns:\n encoder_input: a Tensor, bott...
Please provide a description of the function:def transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, ...
[ "A stack of transformer layers.\n\n Args:\n encoder_input: a Tensor\n encoder_self_attention_bias: bias Tensor for self-attention\n (see common_attention.attention_bias())\n hparams: hyperparameters for model\n name: a string\n nonpadding: optional Tensor with shape [batch_size, encoder_length...
Please provide a description of the function:def transformer_ffn_layer(x, hparams, pad_remover=None, conv_padding="LEFT", nonpadding_mask=None, losses=None, cache=N...
[ "Feed-forward layer in the transformer.\n\n Args:\n x: a Tensor of shape [batch_size, length, hparams.hidden_size]\n hparams: hyperparameters for model\n pad_remover: an expert_utils.PadRemover object tracking the padding\n positions. If provided, when using convolutional settings, the padding\n ...
Please provide a description of the function:def lmx_base(): hparams = transformer.transformer_tpu() # sharing is counterproductive when underparameterized hparams.shared_embedding_and_softmax_weights = False # we judge by log-ppl, so label smoothing hurts. hparams.label_smoothing = 0.0 # This makes the ...
[ "Transformer on languagemodel_lm1b32k_packed. 50M Params." ]
Please provide a description of the function:def lmx_h3k_f12k(): hparams = lmx_base() hparams.hidden_size = 3072 hparams.filter_size = 12288 hparams.batch_size = 2048 hparams.weight_dtype = "bfloat16" return hparams
[ "HParams for training languagemodel_lm1b32k_packed. 880M Params." ]
Please provide a description of the function:def lmx_h4k_f16k(): hparams = lmx_base() hparams.hidden_size = 4096 hparams.filter_size = 16384 hparams.batch_size = 1024 hparams.weight_dtype = "bfloat16" return hparams
[ "HParams for training languagemodel_lm1b32k_packed. 1470M Params." ]
Please provide a description of the function:def lmx_relative(): hparams = lmx_base() hparams.self_attention_type = "dot_product_relative_v2" hparams.activation_dtype = "float32" hparams.weight_dtype = "float32" return hparams
[ "Language model using relative attention." ]
Please provide a description of the function:def lmx_moe_h1k_f4k_x32(): hparams = lmx_h1k_f4k() hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 32 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
[ "Transformer with mixture of experts. 890M Params." ]
Please provide a description of the function:def lmx_moe_h1k_f8k_x16(): hparams = lmx_h1k_f4k() hparams.filter_size = 8192 hparams.ffn_layer = "local_moe_tpu" hparams.moe_num_experts = 16 hparams.weight_dtype = "bfloat16" hparams.batch_size = 8192 return hparams
[ "Transformer with mixture of experts. 890M Params." ]
Please provide a description of the function:def lmx_h1k_f64k(): hparams = lmx_base() hparams.hidden_size = 1024 hparams.filter_size = 65536 hparams.batch_size = 2048 return hparams
[ "HParams for training languagemodel_lm1b32k_packed. 880M Params." ]
Please provide a description of the function:def compute_uncertainty_reward(logits, predictions): # TODO(rsepassi): Add support for L1/L2 loss models. Current code only # works for softmax models. vocab_size = logits.shape[-1] assert vocab_size > 1 log_probs = common_layers.log_prob_from_logits(logits) m...
[ "Uncertainty reward based on logits." ]
Please provide a description of the function:def _reset_non_empty(self, indices): reset_video_op = tf.cond( self._video_condition, lambda: tf.py_func(self._video_reset_writer, [], []), tf.no_op) with tf.control_dependencies([reset_video_op]): inc_op = tf.assign_add(self._episo...
[ "Reset the batch of environments.\n\n Args:\n indices: The batch indices of the environments to reset; defaults to all.\n\n Returns:\n Batch tensor of the new observations.\n " ]
Please provide a description of the function:def set_random_seed(): tf.set_random_seed(FLAGS.random_seed) random.seed(FLAGS.random_seed) np.random.seed(FLAGS.random_seed)
[ "Set the random seed from flag everywhere." ]
Please provide a description of the function:def generate_data_for_problem(problem): training_gen, dev_gen, test_gen = _SUPPORTED_PROBLEM_GENERATORS[problem] num_train_shards = FLAGS.num_shards or 10 tf.logging.info("Generating training data for %s.", problem) train_output_files = generator_utils.train_data...
[ "Generate data for a problem in _SUPPORTED_PROBLEM_GENERATORS." ]
Please provide a description of the function:def generate_data_for_env_problem(problem_name): assert FLAGS.env_problem_max_env_steps > 0, ("--env_problem_max_env_steps " "should be greater than zero") assert FLAGS.env_problem_batch_size > 0, ("--env_problem_batch_si...
[ "Generate data for `EnvProblem`s." ]
Please provide a description of the function:def generate_data_for_registered_problem(problem_name): tf.logging.info("Generating data for %s.", problem_name) if FLAGS.num_shards: raise ValueError("--num_shards should not be set for registered Problem.") problem = registry.problem(problem_name) task_id = ...
[ "Generate data for a registered problem." ]
Please provide a description of the function:def _collect_data(directory): # Returns: data_files = [] transcripts = [ filename for filename in os.listdir(directory) if filename.endswith(".csv") ] for transcript in transcripts: transcript_path = os.path.join(directory, transcript) with o...
[ "Traverses directory collecting input and target files.\n\n Args:\n directory: base path to extracted audio and transcripts.\n Returns:\n list of (media_base, media_filepath, label) tuples\n " ]
Please provide a description of the function:def _file_exists(path, filename): return os.path.isfile(os.path.join(path, filename))
[ "Checks if the filename exists under the path." ]
Please provide a description of the function:def _is_relative(path, filename): return os.path.abspath(os.path.join(path, filename)).startswith(path)
[ "Checks if the filename is relative, not absolute." ]
Please provide a description of the function:def define_ppo_step(data_points, hparams, action_space, lr): observation, action, discounted_reward, norm_advantage, old_pdf = data_points obs_shape = common_layers.shape_list(observation) observation = tf.reshape( observation, [obs_shape[0] * obs_shape[1]] +...
[ "Define ppo step." ]
Please provide a description of the function:def define_ppo_epoch(memory, hparams, action_space, batch_size): observation, reward, done, action, old_pdf, value = memory # This is to avoid propagating gradients through simulated environment. observation = tf.stop_gradient(observation) action = tf.stop_gradie...
[ "PPO epoch." ]
Please provide a description of the function:def calculate_generalized_advantage_estimator( reward, value, done, gae_gamma, gae_lambda): # pylint: disable=g-doc-args # pylint: enable=g-doc-args next_value = value[1:, :] next_not_done = 1 - tf.cast(done[1:, :], tf.float32) delta = (reward[:-1, :] + gae...
[ "Generalized advantage estimator.\n\n Returns:\n GAE estimator. It will be one element shorter than the input; this is\n because to compute GAE for [0, ..., N-1] one needs V for [1, ..., N].\n " ]
Please provide a description of the function:def gym_space_spec(gym_space): # First try to determine the type. try: tf_dtype = tf.as_dtype(gym_space.dtype) except TypeError as e: tf.logging.error("Cannot convert space's type [%s] to tf.dtype", gym_space.dtype) raise e # Now ...
[ "Returns a reading spec of a gym space.\n\n NOTE: Only implemented currently for Box and Discrete.\n\n Args:\n gym_space: instance of gym.spaces whose spec we want.\n\n Returns:\n Reading spec for that space.\n\n Raises:\n NotImplementedError: For spaces whose reading spec we haven't implemented.\n " ...
Please provide a description of the function:def cardinality(gym_space): if (gym_space.dtype == np.float32) or (gym_space.dtype == np.float64): tf.logging.error("Returning None for a float gym space's cardinality: ", gym_space) return None if isinstance(gym_space, Discrete): re...
[ "Number of elements that can be represented by the space.\n\n Makes the most sense for Discrete or Box type with integral dtype, ex: number\n of actions in an action space.\n\n Args:\n gym_space: The gym space.\n\n Returns:\n np.int64 number of observations that can be represented by this space, or\n r...
Please provide a description of the function:def image_rmse(predictions, labels, weights_fn=common_layers.weights_all): if common_layers.shape_list(predictions)[-1] == 1: predictions = tf.squeeze(predictions, axis=[-1]) else: predictions = tf.argmax(predictions, axis=-1) return padded_rmse(predictions,...
[ "RMSE but will argmax if last dim is not 1." ]
Please provide a description of the function:def abs_error(predictions, labels, weights_fn=None): del weights_fn # Unused targets = tf.squeeze(labels, axis=[2, 3]) batch_abs_error = tf.abs(predictions - targets) den = tf.ones(tf.shape(batch_abs_error), dtype=tf.float32) return (batch_abs_error, den)
[ "Computes mean(abs(preds-target))." ]
Please provide a description of the function:def padded_variance_explained(predictions, labels, weights_fn=common_layers.weights_all): predictions, labels = common_layers.pad_with_zeros(predictions, labels) targets = labels weights = weights_fn(target...
[ "Explained variance, also known as R^2." ]
Please provide a description of the function:def padded_accuracy_topk(predictions, labels, k, weights_fn=common_layers.weights_nonzero): with tf.variable_scope("padded_accuracy_topk", values=[predictions, labels]): padded_predictions, p...
[ "Percentage of times that top-k predictions matches labels on non-0s." ]
Please provide a description of the function:def rounding_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): outputs = tf.squeeze(tf.to_int32(predictions), axis=-1) weights = weights_fn(labels) labels = tf.to_int32(lab...
[ "Sequence accuracy for L1/L2 losses: round down the predictions to ints." ]
Please provide a description of the function:def padded_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list(predictions)[-1] == 1: retu...
[ "Percentage of times that predictions matches labels everywhere (non-0)." ]
Please provide a description of the function:def sequence_edit_distance(predictions, labels, weights_fn=common_layers.weights_nonzero): if weights_fn is not common_layers.weights_nonzero: raise ValueError("Only weights_nonzero can be used for this metric.")...
[ "Average edit distance, ignoring padding 0s.\n\n The score returned is the edit distance divided by the total length of\n reference truth and the weight returned is the total length of the truth.\n\n Args:\n predictions: Tensor of shape [`batch_size`, `length`, 1, `num_classes`] and\n type tf.float32 r...
Please provide a description of the function:def padded_neg_log_perplexity(predictions, labels, weights_fn=common_layers.weights_nonzero): num, den = common_layers.padded_cross_entropy( predictions, labels, 0.0, weights_fn=weights_fn, reduce_sum=Fal...
[ "Average log-perplexity exluding padding 0s. No smoothing." ]
Please provide a description of the function:def padded_neg_log_perplexity_with_masking( predictions, labels, features, weights_fn=None): del weights_fn if "targets_mask" not in features: raise ValueError("masked_neg_log_perplexity requires targets_mask feature") # Features are 4 dimension...
[ "Average log-perplexity with custom targets_mask." ]
Please provide a description of the function:def dmol_neg_log_perplexity(predictions, labels, weights_fn=None): del weights_fn # Unused num, den = common_layers.dml_loss( predictions, labels, reduce_sum=False) return (-num, den)
[ "Average log-perplexity excluding padding 0s. No smoothing." ]
Please provide a description of the function:def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): outputs = tf.squeeze(tf.to_int32(predictions)) labels = tf.squeeze(labels) weights = weights_fn(labels) labels = tf.to_int32(labels) ...
[ "Rounding accuracy for L1/L2 losses: round down the predictions to ints." ]
Please provide a description of the function:def padded_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): # If the last dimension is 1 then we're using L1/L2 loss. if common_layers.shape_list(predictions)[-1] == 1: return rounding_accuracy(predic...
[ "Percentage of times that predictions matches labels on non-0s." ]
Please provide a description of the function:def multilabel_accuracy_matchk(predictions, labels, k, weights_fn=common_layers.weights_nonzero): predictions = tf.to_int32(tf.argmax(predictions, axis=-1)) scores = tf.to_flo...
[ "Used to evaluate the VQA accuracy.\n\n Let n be the times that predictions appear in labels, then final score\n is min(n/k, 1).\n Refer to https://arxiv.org/pdf/1505.00468.pdf.\n\n Args:\n predictions: A tensor with shape [batch_size, 1, 1, 1, vocab_size].\n labels: A tensor with shape [batch_size, lengt...
Please provide a description of the function:def set_precision(predictions, labels, weights_fn=common_layers.weights_nonzero): with tf.variable_scope("set_precision", values=[predictions, labels]): labels = tf.squeeze(labels, [2, 3]) weights = weights_fn(labels) labels = tf.one_hot(la...
[ "Precision of set predictions.\n\n Args:\n predictions : A Tensor of scores of shape [batch, nlabels].\n labels: A Tensor of int32s giving true set elements,\n of shape [batch, seq_length].\n weights_fn: A function to weight the elements.\n\n Returns:\n hits: A Tensor of shape [batch, nlabels].\n...
Please provide a description of the function:def image_summary(predictions, targets, hparams): del hparams results = tf.cast(tf.argmax(predictions, axis=-1), tf.uint8) gold = tf.cast(targets, tf.uint8) summary1 = tf.summary.image("prediction", results, max_outputs=2) summary2 = tf.summary.image("data", gol...
[ "Reshapes predictions and passes it to tensorboard.\n\n Args:\n predictions : The predicted image (logits).\n targets : The ground truth.\n hparams: model hparams.\n\n Returns:\n summary_proto: containing the summary images.\n weights: A Tensor of zeros of the same shape as predictions.\n " ]
Please provide a description of the function:def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None): with tf.variable_scope("softmax_cross_entropy_one_hot", values=[logits, labels]): del weights_fn cross_entropy = tf.losses.softmax_cross_entropy( onehot_labels=l...
[ "Calculate softmax cross entropy given one-hot labels and logits.\n\n Args:\n logits: Tensor of size [batch-size, o=1, p=1, num-classes]\n labels: Tensor of size [batch-size, o=1, p=1, num-classes]\n weights_fn: Function that takes in labels and weighs examples (unused)\n Returns:\n cross-entropy (sca...
Please provide a description of the function:def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None): with tf.variable_scope("sigmoid_accuracy_one_hot", values=[logits, labels]): del weights_fn predictions = tf.nn.sigmoid(logits) labels = tf.argmax(labels, -1) predictions = tf.argmax(predicti...
[ "Calculate accuracy for a set, given one-hot labels and logits.\n\n Args:\n logits: Tensor of size [batch-size, o=1, p=1, num-classes]\n labels: Tensor of size [batch-size, o=1, p=1, num-classes]\n weights_fn: Function that takes in labels and weighs examples (unused)\n Returns:\n accuracy (scalar), w...
Please provide a description of the function:def sigmoid_recall_one_hot(logits, labels, weights_fn=None): with tf.variable_scope("sigmoid_recall_one_hot", values=[logits, labels]): del weights_fn num_classes = logits.shape[-1] predictions = tf.nn.sigmoid(logits) predictions = tf.argmax(predictions,...
[ "Calculate recall for a set, given one-hot labels and logits.\n\n Predictions are converted to one-hot,\n as predictions[example][arg-max(example)] = 1\n\n Args:\n logits: Tensor of size [batch-size, o=1, p=1, num-classes]\n labels: Tensor of size [batch-size, o=1, p=1, num-classes]\n weights_fn: Functi...
Please provide a description of the function:def sigmoid_cross_entropy_one_hot(logits, labels, weights_fn=None): with tf.variable_scope("sigmoid_cross_entropy_one_hot", values=[logits, labels]): del weights_fn cross_entropy = tf.losses.sigmoid_cross_entropy( multi_class_lab...
[ "Calculate sigmoid cross entropy for one-hot lanels and logits.\n\n Args:\n logits: Tensor of size [batch-size, o=1, p=1, num-classes]\n labels: Tensor of size [batch-size, o=1, p=1, num-classes]\n weights_fn: Function that takes in labels and weighs examples (unused)\n Returns:\n cross_entropy (scala...
Please provide a description of the function:def roc_auc(logits, labels, weights_fn=None): del weights_fn with tf.variable_scope("roc_auc", values=[logits, labels]): predictions = tf.argmax(logits, axis=-1) _, auc = tf.metrics.auc(labels, predictions, curve="ROC") return auc, tf.constant(1.0)
[ "Calculate ROC AUC.\n\n Requires binary classes.\n\n Args:\n logits: Tensor of size [batch_size, 1, 1, num_classes]\n labels: Tensor of size [batch_size, 1, 1, num_classes]\n weights_fn: Function that takes in labels and weighs examples (unused)\n Returns:\n ROC AUC (scalar), weights\n " ]
Please provide a description of the function:def create_evaluation_metrics(problems, model_hparams): def reduce_dimensions(predictions, labels): # We will treat first dimensions as batch. One example are video frames. if len(predictions.get_shape()) > 5: predictions_shape = common_layers.shape_l...
[ "Creates the evaluation metrics for the model.\n\n Args:\n problems: List of Problem instances.\n model_hparams: a set of hparams.\n\n Returns:\n dict<metric name, metric function>. The metric functions have signature\n (Tensor predictions, features) -> (metric Tensor, update op), where features\n ...
Please provide a description of the function:def create_eager_metrics_for_problem(problem, model_hparams): metric_fns = problem.eval_metric_fns(model_hparams) problem_hparams = problem.get_hparams(model_hparams) target_modality = problem_hparams.modality["targets"] weights_fn = model_hparams.weights_fn.get( ...
[ "See create_eager_metrics." ]
Please provide a description of the function:def create_eager_metrics(metric_names, weights_fn=common_layers.weights_all): metric_fns = dict( [(name, METRICS_FNS[name]) for name in metric_names]) return create_eager_metrics_internal(metric_fns, weights_fn)
[ "Create metrics accumulators and averager for Eager mode.\n\n Args:\n metric_names: list<str> from Metrics enum\n weights_fn: function that takes labels and returns a weights mask. Defaults\n to weights of all 1, i.e. common_layers.weights_all. Use\n common_layers.weights_nonzero if labels have 0-p...
Please provide a description of the function:def create_eager_metrics_internal(metric_fns, weights_fn=common_layers.weights_all): tfe_metrics = {} for name in metric_fns: tfe_metrics[name] = tfe.metrics.Mean(name=name) def metric_accum(predictions, targets): for name...
[ "Create metrics accumulators and averager for Eager mode.\n\n Args:\n metric_fns: dict<metric name, metric function>\n weights_fn: function that takes labels and returns a weights mask. Defaults\n to weights of all 1, i.e. common_layers.weights_all. Use\n common_layers.weights_nonzero if labels hav...
Please provide a description of the function:def word_error_rate(raw_predictions, labels, lookup=None, weights_fn=common_layers.weights_nonzero): def from_tokens(raw, lookup_): gathered = tf.gather(lookup_, tf.cast(raw, tf.int32)) joined = tf.reg...
[ "Calculate word error rate.\n\n Args:\n raw_predictions: The raw predictions.\n labels: The actual labels.\n lookup: A tf.constant mapping indices to output tokens.\n weights_fn: Weighting function.\n\n Returns:\n The word error rate.\n ", "Convert ascii+2 encoded codes to string-tokens." ]
Please provide a description of the function:def pearson_correlation_coefficient(predictions, labels, weights_fn=None): del weights_fn _, pearson = tf.contrib.metrics.streaming_pearson_correlation(predictions, labels) return pearson, tf.constant(1...
[ "Calculate pearson correlation coefficient.\n\n Args:\n predictions: The raw predictions.\n labels: The actual labels.\n weights_fn: Weighting function.\n\n Returns:\n The pearson correlation coefficient.\n " ]
Please provide a description of the function:def attention_lm_prepare_decoder(targets, hparams): if hparams.prepend_mode == "prepend_inputs_full_attention": decoder_self_attention_bias = ( common_attention.attention_bias_prepend_inputs_full_attention( common_attention.embedding_to_padding(t...
[ "Prepare one shard of the model for the decoder.\n\n Args:\n targets: a Tensor.\n hparams: run hyperparameters\n\n Returns:\n decoder_input: a Tensor, bottom of decoder stack\n decoder_self_attention_bias: a Tensor, containing large negative values\n to implement masked attention and possibly biase...
Please provide a description of the function:def attention_lm_decoder(decoder_input, decoder_self_attention_bias, hparams, name="decoder"): x = decoder_input with tf.variable_scope(name): for layer in range(hparams.num_hidden_layers):...
[ "A stack of attention_lm layers.\n\n Args:\n decoder_input: a Tensor\n decoder_self_attention_bias: bias Tensor for self-attention\n (see common_attention.attention_bias())\n hparams: hyperparameters for model\n name: a string\n\n Returns:\n y: a Tensors\n " ]
Please provide a description of the function:def attention_lm_base(): hparams = common_hparams.basic_params1() hparams.hidden_size = 1024 hparams.batch_size = 8192 hparams.max_length = 256 hparams.dropout = 0.0 hparams.clip_grad_norm = 0. # i.e. no gradient clipping hparams.optimizer_adam_epsilon = 1e...
[ "Set of hyperparameters." ]
Please provide a description of the function:def attention_lm_small(): hparams = attention_lm_base() hparams.num_hidden_layers = 4 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.layer_prepostprocess_dropout = 0.5 return hparams
[ "Cheap model.\n\n on lm1b_32k:\n 45M params\n 2 steps/sec on [GeForce GTX TITAN X]\n\n Returns:\n an hparams object.\n " ]
Please provide a description of the function:def attention_lm_translation(): hparams = attention_lm_base() hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.max_length = 512 hpar...
[ "Version to use for seq2seq." ]
Please provide a description of the function:def _get_ngrams(segment, max_order): ngram_counts = collections.Counter() for order in range(1, max_order + 1): for i in range(0, len(segment) - order + 1): ngram = tuple(segment[i:i + order]) ngram_counts[ngram] += 1 return ngram_counts
[ "Extracts all n-grams up to a given maximum order from an input segment.\n\n Args:\n segment: text segment from which n-grams will be extracted.\n max_order: maximum length in tokens of the n-grams returned by this\n methods.\n\n Returns:\n The Counter containing all n-grams up to max_order in seg...
Please provide a description of the function:def bleu_score(predictions, labels, **unused_kwargs): outputs = tf.to_int32(tf.argmax(predictions, axis=-1)) # Convert the outputs and labels to a [batch_size, input_length] tensor. outputs = tf.squeeze(outputs, axis=[-1, -2]) labels = tf.squeeze(labels, axis=[-1,...
[ "BLEU score computation between labels and predictions.\n\n An approximate BLEU scoring method since we do not glue word pieces or\n decode the ids and tokenize the output. By default, we use ngram order of 4\n and use brevity penalty. Also, this does not have beam search.\n\n Args:\n predictions: tensor, mo...
Please provide a description of the function:def bleu_tokenize(string): r string = uregex.nondigit_punct_re.sub(r"\1 \2 ", string) string = uregex.punct_nondigit_re.sub(r" \1 \2", string) string = uregex.symbol_re.sub(r" \1 ", string) return string.split()
[ "Tokenize a string following the official BLEU implementation.\n\n See https://github.com/moses-smt/mosesdecoder/\"\n \"blob/master/scripts/generic/mteval-v14.pl#L954-L983\n In our case, the input string is expected to be just one line\n and no HTML entities de-escaping is needed.\n So we just tokeniz...
Please provide a description of the function:def bleu_wrapper(ref_filename, hyp_filename, case_sensitive=False): ref_lines = text_encoder.native_to_unicode( tf.gfile.Open(ref_filename, "r").read()).split("\n") hyp_lines = text_encoder.native_to_unicode( tf.gfile.Open(hyp_filename, "r").read()).split(...
[ "Compute BLEU for two files (reference and hypothesis translation)." ]
Please provide a description of the function:def _try_twice_tf_glob(pattern): try: return tf.gfile.Glob(pattern) except tf.errors.NotFoundError: return tf.gfile.Glob(pattern)
[ "Glob twice, first time possibly catching `NotFoundError`.\n\n tf.gfile.Glob may crash with\n\n ```\n tensorflow.python.framework.errors_impl.NotFoundError:\n xy/model.ckpt-1130761_temp_9cb4cb0b0f5f4382b5ea947aadfb7a40;\n No such file or directory\n ```\n\n Standard glob.glob does not have this bug, but does...
Please provide a description of the function:def _read_stepfiles_list(path_prefix, path_suffix=".index", min_steps=0): stepfiles = [] for filename in _try_twice_tf_glob(path_prefix + "*-[0-9]*" + path_suffix): basename = filename[:-len(path_suffix)] if path_suffix else filename try: steps = int(bas...
[ "Return list of StepFiles sorted by step from files at path_prefix." ]
Please provide a description of the function:def stepfiles_iterator(path_prefix, wait_minutes=0, min_steps=0, path_suffix=".index", sleep_sec=10): # Wildcard D*-[0-9]* does not match D/x-1, so if D is a directory let # path_prefix="D/". if not path_prefix.endswith(os.sep) and os.path.isd...
[ "Continuously yield new files with steps in filename as they appear.\n\n This is useful for checkpoint files or other files whose names differ just in\n an integer marking the number of steps and match the wildcard path_prefix +\n \"*-[0-9]*\" + path_suffix.\n\n Unlike `tf.contrib.training.checkpoints_iterator`...
Please provide a description of the function:def _get_vqa_v2_annotations(directory, annotation_url, annotation_filename="vqa_v2.tar.gz"): annotation_file = generator_utils.maybe_download_from_drive( directory, annotation_filename, annotation_url) with...
[ "Extract the VQA V2 annotation files to directory unless it's there." ]