Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def deep_discriminator(x, batch_norm, is_training, filters=64, filter_size=4, stride=2, output_size=1024): with tf.variable_scope( ...
[ "Discriminator architecture based on InfoGAN." ]
Please provide a description of the function:def instance_norm(x): with tf.variable_scope("instance_norm"): epsilon = 1e-5 mean, var = tf.nn.moments(x, [1, 2], keep_dims=True) scale = tf.get_variable( "scale", [x.get_shape()[-1]], initializer=tf.truncated_normal_initializer(mean=1.0, st...
[ "Instance normalization layer." ]
Please provide a description of the function:def general_conv(x, num_filters=64, filter_size=7, stride=1, stddev=0.02, padding="VALID", name="conv", do_norm="instance", do_relu=True, ...
[ "Generalized convolution layer." ]
Please provide a description of the function:def patch_discriminator(x, filters=64, filter_size=5, n=4, name="patch_discrim"): with tf.variable_scope(name): x_shape = shape_list(x) spatial_dims = [x_shape[1] // 4, x_shape[2] // 4] x = tf.random_crop(x, [x_shape[0]] + spatial_dim...
[ "Patch descriminator." ]
Please provide a description of the function:def mean_with_attention(x, name, num_heads=4): with tf.variable_scope(name): shape = shape_list(x) m = tf.reduce_mean(x, [1, 2]) a = layers().Dense(num_heads, name="mean_attn")(x) s = tf.reshape(a, [shape[0], -1, num_heads]) s = tf.nn.softmax(s, axis...
[ "Mean and attention to reduce spatial dimensions." ]
Please provide a description of the function:def single_discriminator(x, filters=128, kernel_size=8, strides=4, pure_mean=False): with tf.variable_scope("discriminator"): net = layers().Conv2D( filters, kernel_size, strides=strides, padding="SAME", name="conv1")(x) if pure_...
[ "A simple single-layer convolutional discriminator." ]
Please provide a description of the function:def double_discriminator(x, filters1=128, filters2=None, kernel_size=8, strides=4, pure_mean=False): if filters2 is None: filters2 = 4 * filters1 with tf.variable_scope("discriminator"): batch_size = shape_list(x)[0] net = layers()...
[ "A convolutional discriminator with 2 layers and concatenated output." ]
Please provide a description of the function:def upscale(inputs, f, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR): height, width = shape_list(inputs)[1:3] # pylint: disable=unbalanced-tuple-unpacking return tf.image.resize_images(inputs, (height * f, width * f), method)
[ "Upscaling the image by a factor of f." ]
Please provide a description of the function:def cyclegan_upsample(net, num_outputs, stride, method="conv2d_transpose"): with tf.variable_scope("upconv"): net_shape = tf.shape(net) height = net_shape[1] width = net_shape[2] # Reflection pad by 1 in spatial dimensions (axes 1, 2 = h, w) to make a ...
[ "Upsamples the given inputs.\n\n Args:\n net: A Tensor of size [batch_size, height, width, filters].\n num_outputs: The number of output filters.\n stride: A list of 2 scalars or a 1x2 Tensor indicating the scale,\n relative to the inputs, of the output dimensions. For example, if kernel\n size ...
Please provide a description of the function:def weight_targeting(w, k): k = tf.to_int32(k) w_shape = shape_list(w) size = tf.to_int32(tf.reduce_prod(w_shape[:-1])) w = tf.reshape(w, [size, w_shape[-1]]) transpose_w = tf.transpose(w) thres = tf.contrib.framework.sort(tf.abs(transpose_w), axis=1)[:, k] ...
[ "Weight-level magnitude pruning." ]
Please provide a description of the function:def unit_targeting(w, k): k = tf.to_int32(k) w_shape = shape_list(w) size = tf.to_int32(tf.reduce_prod(w_shape[:-1])) w = tf.reshape(w, [size, w_shape[-1]]) norm = tf.norm(w, axis=0) thres = tf.contrib.framework.sort(norm, axis=0)[k] mask = to_float(thres >...
[ "Unit-level magnitude pruning." ]
Please provide a description of the function:def td_conv(inputs, filters, kernel_size, targeting_count, targeting_fn, keep_prob, is_training, do_prune=True, strides=(1, 1), padding="valid", data_forma...
[ "Apply targeted dropout to the weights of a convolution." ]
Please provide a description of the function:def targeted_dropout(inputs, k, keep_prob, targeting_fn, is_training, do_prune=False): if not is_training and do_prune: k = tf.round(to_float(k) * to_float(1. - ...
[ "Applies targeted dropout.\n\n Applies dropout at a rate of `1 - keep_prob` to only those elements of\n `inputs` marked by `targeting_fn`. See below and paper for more detail:\n\n \"Targeted Dropout for Posthoc Pruning\" Aidan N. Gomez, Ivan Zhang,\n Kevin Swersky, Yarin Gal, and Geoffrey E. Hinton.\n\n Args...
Please provide a description of the function:def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0): batch_size = shape_list(mu)[0] prior_distribution = tfp.distributions.Normal( mu_p, tf.exp(tf.multiply(0.5, log_var_p))) posterior_distribution = tfp.distributions.Normal( mu, tf.exp(tf.multiply(0...
[ "KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).\n\n Args:\n mu: mu parameter of the distribution.\n log_var: log(var) parameter of the distribution.\n mu_p: optional mu from a learned prior distribution\n log_var_p: optional log(var) from a learned prior distribution\n Returns:\n ...
Please provide a description of the function:def to_tensor(self): a_shape = shape_list(self.a) b_shape = shape_list(self.b) inner_dim = b_shape[1] result_dim = b_shape[0] flat_a = tf.reshape(self.a, [-1, inner_dim]) product = tf.matmul(flat_a, self.b, transpose_b=True) product_shape = a...
[ "Convert to Tensor." ]
Please provide a description of the function:def _compute_weights(self): with tf.variable_scope("compute_weights"): self.layer.kernel = tf.nn.l2_normalize( self.layer.v, axis=self.norm_axes) * self.layer.g
[ "Generate weights with normalization." ]
Please provide a description of the function:def _init_norm(self, weights): with tf.variable_scope("init_norm"): flat = tf.reshape(weights, [-1, self.layer_depth]) return tf.reshape(tf.norm(flat, axis=0), (self.layer_depth,))
[ "Set the norm of the weight vector." ]
Please provide a description of the function:def _data_dep_init(self, inputs): with tf.variable_scope("data_dep_init"): # Generate data dependent init values activation = self.layer.activation self.layer.activation = None x_init = self.layer.call(inputs) m_init, v_init = tf.momen...
[ "Data dependent initialization for eager execution." ]
Please provide a description of the function:def build(self, input_shape=None): input_shape = tf.TensorShape(input_shape).as_list() self.input_spec = layers().InputSpec(shape=input_shape) if not self.layer.built: self.layer.build(input_shape) self.layer.built = False if not hasattr(...
[ "Build `Layer`." ]
Please provide a description of the function:def call(self, inputs): # if context.executing_eagerly(): # if not self.initialized: # self._data_dep_init(inputs) self._compute_weights() # Recompute weights for each forward pass output = self.layer.call(inputs) return output
[ "Call `Layer`." ]
Please provide a description of the function:def compute_mean_reward(rollouts, clipped): reward_name = "reward" if clipped else "unclipped_reward" rewards = [] for rollout in rollouts: if rollout[-1].done: rollout_reward = sum(getattr(frame, reward_name) for frame in rollout) rewards.append(rol...
[ "Calculate mean rewards from given epoch." ]
Please provide a description of the function:def evaluate_single_config( hparams, sampling_temp, max_num_noops, agent_model_dir, eval_fn=_eval_fn_with_learner ): tf.logging.info("Evaluating metric %s", get_metric_name( sampling_temp, max_num_noops, clipped=False )) eval_hparams = trainer_lib.crea...
[ "Evaluate the PPO agent in the real environment." ]
Please provide a description of the function:def evaluate_all_configs( hparams, agent_model_dir, eval_fn=_eval_fn_with_learner ): metrics = {} # Iterate over all combinations of sampling temperatures and whether to do # initial no-ops. for sampling_temp in hparams.eval_sampling_temps: # Iterate over ...
[ "Evaluate the agent with multiple eval configurations." ]
Please provide a description of the function:def evaluate_world_model( real_env, hparams, world_model_dir, debug_video_path, split=tf.estimator.ModeKeys.EVAL, ): frame_stack_size = hparams.frame_stack_size rollout_subsequences = [] def initial_frame_chooser(batch_size): assert batch_size == len(rol...
[ "Evaluate the world model (reward accuracy).", "Add a debug frame." ]
Please provide a description of the function:def summarize_metrics(eval_metrics_writer, metrics, epoch): for (name, value) in six.iteritems(metrics): summary = tf.Summary() summary.value.add(tag=name, simple_value=value) eval_metrics_writer.add_summary(summary, epoch) eval_metrics_writer.flush()
[ "Write metrics to summary." ]
Please provide a description of the function:def full_game_name(short_name): camel_game_name = misc_utils.snakecase_to_camelcase(short_name) full_name = camel_game_name + ATARI_GAME_MODE return full_name
[ "CamelCase game name with mode suffix.\n\n Args:\n short_name: snake_case name without mode e.g \"crazy_climber\"\n\n Returns:\n full game name e.g. \"CrazyClimberNoFrameskip-v4\"\n " ]
Please provide a description of the function:def setup_env(hparams, batch_size, max_num_noops, rl_env_max_episode_steps=-1, env_name=None): if not env_name: env_name = full_game_name(hparams.game) maxskip_envs = should_apply_max_and_skip_env(hparams) ...
[ "Setup." ]
Please provide a description of the function:def update_hparams_from_hparams(target_hparams, source_hparams, prefix): for (param_name, param_value) in six.iteritems(source_hparams.values()): if param_name.startswith(prefix): target_hparams.set_hparam(param_name[len(prefix):], param_value)
[ "Copy a subset of hparams to target_hparams." ]
Please provide a description of the function:def random_rollout_subsequences(rollouts, num_subsequences, subsequence_length): def choose_subsequence(): # TODO(koz4k): Weigh rollouts by their lengths so sampling is uniform over # frames and not rollouts. rollout = random.choice(rollouts) try: ...
[ "Chooses a random frame sequence of given length from a set of rollouts." ]
Please provide a description of the function:def make_initial_frame_chooser( real_env, frame_stack_size, simulation_random_starts, simulation_flip_first_random_for_beginning, split=tf.estimator.ModeKeys.TRAIN, ): initial_frame_rollouts = real_env.current_epoch_rollouts( split=split, minimal_rollo...
[ "Make frame chooser.\n\n Args:\n real_env: T2TEnv to take initial frames from.\n frame_stack_size (int): Number of consecutive frames to extract.\n simulation_random_starts (bool): Whether to choose frames at random.\n simulation_flip_first_random_for_beginning (bool): Whether to flip the first\n ...
Please provide a description of the function:def absolute_hinge_difference(arr1, arr2, min_diff=10, dtype=np.uint8): diff = np.abs(arr1.astype(np.int) - arr2, dtype=np.int) return np.maximum(diff - min_diff, 0).astype(dtype)
[ "Point-wise, hinge loss-like, difference between arrays.\n\n Args:\n arr1: integer array to compare.\n arr2: integer array to compare.\n min_diff: minimal difference taken into consideration.\n dtype: dtype of returned array.\n\n Returns:\n array\n " ]
Please provide a description of the function:def augment_observation( observation, reward, cum_reward, frame_index, bar_color=None, header_height=27 ): img = PIL_Image().new( "RGB", (observation.shape[1], header_height,) ) draw = PIL_ImageDraw().Draw(img) draw.text( (1, 0), "c:{:3}, r:{:3...
[ "Augments an observation with debug info." ]
Please provide a description of the function:def run_rollouts( env, agent, initial_observations, step_limit=None, discount_factor=1.0, log_every_steps=None, video_writers=(), color_bar=False, many_rollouts_from_each_env=False ): assert step_limit is not None or not many_rollouts_from_each_env, ( ...
[ "Runs a batch of rollouts from given initial observations." ]
Please provide a description of the function:def set_initial_state(self, initial_state, initial_frames): self.env.set_initial_state(initial_state, initial_frames) self._initial_frames = initial_frames
[ "Sets the state that will be used on next reset." ]
Please provide a description of the function:def _maybe_download_corpora(tmp_dir, dataset_split): cnn_filename = "cnn_stories.tgz" cnn_finalpath = os.path.join(tmp_dir, "cnn/stories/") dailymail_filename = "dailymail_stories.tgz" dailymail_finalpath = os.path.join(tmp_dir, "dailymail/stories/") if not tf.g...
[ "Download corpora if necessary and unzip them.\n\n Args:\n tmp_dir: directory containing dataset.\n dataset_split: whether we're in train/dev/test mode.\n\n Returns:\n List of all files generated and path to file containing\n train/dev/test split info.\n " ]
Please provide a description of the function:def example_splits(url_file, all_files): def generate_hash(inp): h = hashlib.sha1() h.update(inp) return h.hexdigest() all_files_map = {f.split("/")[-1]: f for f in all_files} urls = [line.strip().encode("utf-8") for line in tf.gfile.Open(url_fil...
[ "Generate splits of the data.", "Generate a sha1 hash to match the raw url to the filename extracted." ]
Please provide a description of the function:def example_generator(all_files, urls_path, sum_token): def fix_run_on_sents(line): if u"@highlight" in line: return line if not line: return line if line[-1] in END_TOKENS: return line return line + u"." filelist = example_splits(u...
[ "Generate examples." ]
Please provide a description of the function:def write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir): def write_to_file(all_files, urls_path, tmp_dir, filename): with io.open( os.path.join(tmp_dir, filename + ".source"), "w", encoding="utf-8") as fstory: with io.op...
[ "Write text to files.", "Write text to files." ]
Please provide a description of the function:def infer_last_epoch_num(data_dir): names = os.listdir(data_dir) epochs_str = [re.findall(pattern=r".*\.(-?\d+)$", string=name) for name in names] epochs_str = sum(epochs_str, []) return max([int(epoch_str) for epoch_str in epochs_str])
[ "Infer highest epoch number from file names in data_dir." ]
Please provide a description of the function:def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None): t2t_env = rl_utils.setup_env( hparams, batch_size=hparams.real_batch_size, max_num_noops=hparams.max_num_noops ) # Load data. if which_epoch_data is not None: if which_epoch_data =...
[ "Load T2TGymEnv with data from one epoch.\n\n Args:\n hparams: hparams.\n data_dir: data directory.\n which_epoch_data: data from which epoch to load.\n\n Returns:\n env.\n " ]
Please provide a description of the function:def infer_game_name_from_filenames(data_dir, snake_case=True): names = os.listdir(data_dir) game_names = [re.findall(pattern=r"^Gym(.*)NoFrameskip", string=name) for name in names] assert game_names, "No data files found in {}".format(data_dir) gam...
[ "Infer name from filenames." ]
Please provide a description of the function:def wrap_with_monitor(env, video_dir): env = ExtendToEvenDimentions(env) env = RenderObservations(env) # pylint: disable=redefined-variable-type env = gym.wrappers.Monitor(env, video_dir, force=True, video_callable=lambda idx: True, ...
[ "Wrap environment with gym.Monitor.\n\n Video recording provided by Monitor requires\n 1) both height and width of observation to be even numbers.\n 2) rendering of environment\n\n Args:\n env: environment.\n video_dir: video directory.\n\n Returns:\n wrapped environment.\n " ]
Please provide a description of the function:def create_simulated_env( output_dir, grayscale, resize_width_factor, resize_height_factor, frame_stack_size, generative_model, generative_model_params, random_starts=True, which_epoch_data="last", **other_hparams ): # We need these, to initialize T2TGymEnv,...
[ "\"Create SimulatedEnv with minimal subset of hparams." ]
Please provide a description of the function:def infer_paths(output_dir, **subdirs): directories = {} for name, path in six.iteritems(subdirs): directories[name] = path if path else os.path.join(output_dir, name) directories["output_dir"] = output_dir return directories
[ "Infers standard paths to policy and model directories.\n\n Example:\n >>> infer_paths(\"/some/output/dir/\", policy=\"\", model=\"custom/path\")\n {\"policy\": \"/some/output/dir/policy\", \"model\": \"custom/path\",\n \"output_dir\":\"/some/output/dir/\"}\n\n Args:\n output_dir: output directory.\n ...
Please provide a description of the function:def add_to_initial_stack(self, frame): if not self._setable_initial_frames: raise ValueError( "This instance does not allow to manually set initial frame stack.") assert_msg = "{}, {}".format(frame.shape, self._initial_frames.shape[:1]) asser...
[ "Adds new frame to (initial) frame stack, removes last one." ]
Please provide a description of the function:def observation(self, frame): if frame.shape == self.observation_space.shape: return frame else: extended_frame = np.zeros(self.observation_space.shape, self.observation_space.dtype) assert self.HW_AXES == (0, 1)...
[ "Add single zero row/column to observation if needed." ]
Please provide a description of the function:def infer(self, ob): self._add_to_stack(ob) logits, vf = self.infer_from_frame_stack(self._frame_stack) return logits, vf
[ "Add new observation to frame stack and infer policy.\n\n Args:\n ob: array of shape (height, width, channels)\n\n Returns:\n logits and vf.\n " ]
Please provide a description of the function:def infer_from_frame_stack(self, ob_stack): logits, vf = self.sess.run([self.logits_t, self.value_function_t], feed_dict={self.obs_t: ob_stack}) return logits, vf
[ "Infer policy from stack of observations.\n\n Args:\n ob_stack: array of shape (1, frame_stack_size, height, width, channels)\n\n Returns:\n logits and vf.\n " ]
Please provide a description of the function:def _normalize_string(raw_str): return " ".join( token.strip() for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str)))
[ "Normalizes the string using tokenizer.encode.\n\n Args:\n raw_str: the input string\n\n Returns:\n A string which is ready to be tokenized using split()\n " ]
Please provide a description of the function:def _prepare_babi_data(tmp_dir, data_dir): if not tf.gfile.Exists(data_dir): tf.gfile.MakeDirs(data_dir) file_path = os.path.join(tmp_dir, _TAR) headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) " "AppleWebKit/...
[ "Downloads and extracts the dataset.\n\n Args:\n tmp_dir: temp directory to download and extract the dataset\n data_dir: The base directory where data and vocab files are stored.\n\n Returns:\n tmp_dir: temp directory containing the raw data.\n " ]
Please provide a description of the function:def _babi_parser(tmp_dir, babi_task_id, subset, dataset_split, joint_training=True): def _data_file(mode, task_id): file_name = (_TASKS[task_id] + "_{}.txt") return os.path.join(_DIR_NAME,...
[ "Parsing the bAbi dataset (train and test).\n\n Args:\n tmp_dir: temp directory to download and extract the dataset\n babi_task_id: babi task id\n subset: babi subset\n dataset_split: dataset split (train or eval)\n joint_training: if training the model on all tasks.\n\n Returns:\n babi_instanc...
Please provide a description of the function:def _register_babi_problems(): for (subset, subset_suffix) in [("en", "_1k"), ("en-10k", "_10k")]: for problem_name, babi_task_id in six.iteritems(_problems_to_register()): problem_class = type("BabiQaConcat" + problem_name + subset_suffix, ...
[ "It dynamically instantiates a class for each babi subsets-tasks.\n\n @registry.register_problem\n class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem):\n @property\n def babi_task_id(self):\n return \"qa0\"\n @property\n def babi_subset(self):\n return \"en-10k\"\n\n It does not...
Please provide a description of the function:def get_labels_encoder(self, data_dir): label_filepath = os.path.join(data_dir, self.vocab_filename) return text_encoder.TokenTextEncoder(label_filepath)
[ "Builds encoder for the given class labels.\n\n Args:\n data_dir: data directory\n\n Returns:\n An encoder for class labels.\n " ]
Please provide a description of the function:def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): generator = self.generate_samples(data_dir, tmp_dir, dataset_split) encoder = self.get_or_create_vocab(data_dir, tmp_dir) label_encoder = self.get_labels_encoder(data_dir) for sample i...
[ "A generator that generates samples that are encoded.\n\n Args:\n data_dir: data directory\n tmp_dir: temp directory\n dataset_split: dataset split\n\n Yields:\n A dict.\n\n " ]
Please provide a description of the function:def feature_encoders(self, data_dir): encoders = (super(BabiQa, self).feature_encoders(data_dir)) label_encoder = self.get_labels_encoder(data_dir) encoders["targets"] = label_encoder # bAbi as a classification task return encoders
[ "Return a dict for encoding and decoding inference input/output.\n\n Args:\n data_dir: data directory\n\n Returns:\n A dict of <feature name, TextEncoder>.\n\n " ]
Please provide a description of the function:def hparams(self, defaults, unused_model_hparams): (super(BabiQa, self).hparams(defaults, unused_model_hparams)) p = defaults num_classes = self._encoders["targets"].vocab_size p.modality = {"targets": modalities.ModalityType.CLASS_LABEL} p.vocab_siz...
[ "Returns problem_hparams.\n\n Args:\n defaults: default hyperparameters\n unused_model_hparams: model hyperparameters\n\n " ]
Please provide a description of the function:def dataset_splits(self): return [{ "split": problem.DatasetSplit.TRAIN, "shards": self.num_train_shards, }, { "split": problem.DatasetSplit.EVAL, "shards": self.num_eval_shards, }, { "split": problem.DatasetSplit.TEST...
[ "Splits of data to produce and number the output shards for each." ]
Please provide a description of the function:def _collect_data(directory, input_ext, transcription_ext): # Directory from string to tuple pair of strings # key: the filepath to a datafile including the datafile's basename. Example, # if the datafile was "/path/to/datafile.wav" then the key would be # "/p...
[ "Traverses directory collecting input and target files." ]
Please provide a description of the function:def add_librispeech_hparams(hparams): hparams.batch_size = 36 hparams.audio_compression = 8 hparams.hidden_size = 2048 hparams.max_input_seq_length = 600000 hparams.max_target_seq_length = 350 hparams.max_length = hparams.max_input_seq_length hparams.min_len...
[ "Adding to base hparams the attributes for for librispeech." ]
Please provide a description of the function:def words_and_tags_from_wsj_tree(tree_string): stack, tags, words = [], [], [] for tok in tree_string.strip().split(): if tok[0] == "(": symbol = tok[1:] tags.append(symbol) stack.append(symbol) else: assert tok[-1] == ")" stack.p...
[ "Generates linearized trees and tokens from the wsj tree format.\n\n It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449.\n\n Args:\n tree_string: tree in wsj format\n\n Returns:\n tuple: (words, linearized tree)\n " ]
Please provide a description of the function:def token_generator(tree_path, source_token_vocab, target_token_vocab, eos=None): eos_list = [] if eos is None else [eos] with tf.gfile.GFile(tree_path, mode="r") as tree_file: tree_line = tree_file.readline() while tree_line: source,...
[ "Generator for parsing as a sequence-to-sequence task that uses tokens.\n\n This generator assumes the files at source_path and target_path have\n the same number of lines and yields dictionaries of \"inputs\" and \"targets\"\n where inputs and targets are token ids from source and target lines\n converted to i...
Please provide a description of the function:def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size, target_vocab_size): # TODO(lukaszkaiser): Correct these calls to generate vocabularies. No data # sources are being passed. del (data_dir, tmp_dir, train, source_voc...
[ "Generator for parsing as a sequence-to-sequence task that uses tokens.\n\n This generator assumes the files parsing_{train,dev}.trees, which contain\n trees in WSJ format.\n\n Args:\n data_dir: path to the data directory.\n tmp_dir: path to temporary storage directory.\n train: whether we're training o...
Please provide a description of the function:def aggregate_stats(stats_files): all_stats = {} for fname in stats_files: with tf.gfile.Open(fname) as f: stats = json.loads(f.read()) for k, v in stats.iteritems(): if k not in all_stats: if isinstance(v, list): all_stat...
[ "Aggregate stats in per-shard stats files." ]
Please provide a description of the function:def filename_to_task_id(fname): # This matches the order and size in WikisumBase.out_filepaths fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev": 800, "test": 900, } parts = fname.split("-") split = parts[1] shard_id ...
[ "Map filename to the task id that created it assuming 1k tasks." ]
Please provide a description of the function:def validate_data_files(problem, data_files, min_size): # Check that all files are present data_dir = os.path.split(data_files[0])[0] out_filepaths = problem.out_filepaths(data_dir) missing_filepaths = set(out_filepaths) - set(data_files) if missing_filepaths: ...
[ "Validate presence and minimum size of files." ]
Please provide a description of the function:def distill_resnet_32_to_15_cifar20x5(): hparams = distill_base() hparams.teacher_model = "resnet" hparams.teacher_hparams = "resnet_cifar_32" hparams.student_model = "resnet" hparams.student_hparams = "resnet_cifar_15" hparams.optimizer_momentum_nesterov = T...
[ "Set of hyperparameters." ]
Please provide a description of the function:def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename): if not tf.gfile.Exists(data_dir): tf.gfile.MakeDirs(data_dir) file_path = generator_utils.maybe_download(tmp_dir, _TAR, _URL) tar_all = tarfile.open(file_path) tar_all.extractall(tmp_d...
[ "Downloading and preparing the dataset.\n\n Args:\n tmp_dir: tem directory\n data_dir: data directory\n vocab_size: size of vocabulary\n vocab_filename: name of vocab file\n\n " ]
Please provide a description of the function:def get_dataset_split(tmp_dir, split, use_control_set): if not use_control_set: dataset_split = { problem.DatasetSplit.TRAIN: [ f for f in tf.gfile.Glob( os.path.join(tmp_dir, "train-novels/*/*.txt")) ], problem.Da...
[ "Gives the file paths with regards to the given split.\n\n Args:\n tmp_dir: temp directory\n split: dataset split\n use_control_set: uses control dataset if true.\n\n Returns:\n list of file paths.\n\n " ]
Please provide a description of the function:def min_sequence_length(self, dataset_split): return { problem.DatasetSplit.TRAIN: 8, problem.DatasetSplit.EVAL: 65, problem.DatasetSplit.TEST: 65 }[dataset_split]
[ "Determine the minimum sequence length given a dataset_split.\n\n Args:\n dataset_split: A problem.DatasetSplit.\n\n Returns:\n The minimum length that a sequence can be for this dataset_split.\n " ]
Please provide a description of the function:def max_sequence_length(self, dataset_split): return { problem.DatasetSplit.TRAIN: 64, problem.DatasetSplit.EVAL: 128, problem.DatasetSplit.TEST: 128 }[dataset_split]
[ "Determine the maximum sequence length given a dataset_split.\n\n Args:\n dataset_split: A problem.DatasetSplit.\n\n Returns:\n The maximum length that a sequence can be for this dataset_split.\n " ]
Please provide a description of the function:def num_samples(self, dataset_split): return { problem.DatasetSplit.TRAIN: 1000000, problem.DatasetSplit.EVAL: 10000, problem.DatasetSplit.TEST: 10000 }[dataset_split]
[ "Determine the dataset sized given a dataset_split.\n\n Args:\n dataset_split: A problem.DatasetSplit.\n\n Returns:\n The desired number of samples for this dataset_split.\n " ]
Please provide a description of the function:def next_checkpoint(model_dir, timeout_mins=240): last_ckpt = None timeout_secs = None if timeout_mins != -1: timeout_secs = timeout_mins * 60 while True: last_ckpt = tf.contrib.training.wait_for_new_checkpoint( model_dir, last_ckpt, seconds_to_sle...
[ "Yields successive checkpoints from model_dir.\n\n Args:\n model_dir: The directory in which checkpoints are saved.\n timeout_mins: The maximum amount of time in minutes to wait\n between checkpoints. Set this to -1 to wait indefinitely.\n Yields:\n last_ckpt: a new checkpoint path, or N...
Please provide a description of the function:def next_undecoded_checkpoint(model_dir, timeout_mins=240): last_ckpt = None last_step = 0 while True: # Get the latest checkpoint. last_ckpt = tf.contrib.training.wait_for_new_checkpoint( model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 * timeo...
[ "Yields successive checkpoints from model_dir." ]
Please provide a description of the function:def create_session_config(log_device_placement=False, enable_graph_rewriter=False, gpu_mem_fraction=0.95, use_tpu=False, xla_jit_level=tf.OptimizerOptions.OFF, ...
[ "The TensorFlow Session config to use." ]
Please provide a description of the function:def create_run_config(model_name, master="", model_dir=None, iterations_per_loop=1000, num_shards=8, log_device_placement=False, save_checkpoin...
[ "Create RunConfig, TPUConfig, and Parallelism object." ]
Please provide a description of the function:def create_estimator(model_name, hparams, run_config, schedule="train_and_evaluate", decode_hparams=None, use_tpu=False, use_tpu_estimator=False, ...
[ "Create a T2T Estimator." ]
Please provide a description of the function:def create_hooks(use_tfdbg=False, use_dbgprofile=False, dbgprofile_kwargs=None, use_validation_monitor=False, validation_monitor_kwargs=None, use_early_stopping=False, early...
[ "Create train and eval hooks for Experiment." ]
Please provide a description of the function:def create_experiment( run_config, hparams, model_name, problem_name, data_dir, train_steps, eval_steps, min_eval_frequency=2000, eval_throttle_seconds=600, schedule="train_and_evaluate", export=False, decode_hparams=None, ...
[ "Create Experiment." ]
Please provide a description of the function:def create_experiment_fn(*args, **kwargs): def experiment_fn(run_config, hparams): return create_experiment(run_config, hparams, *args, **kwargs) return experiment_fn
[ "Wrapper for canonical experiment_fn. See create_experiment." ]
Please provide a description of the function:def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False): ckpt = tf.train.get_checkpoint_state(ckpt_dir) if must_restore and not ckpt: raise ValueError("No checkpoint found in %s" % ckpt_dir) if not ckpt: return 0 path = ckpt.model_checkpoint_pat...
[ "Restore from a checkpoint." ]
Please provide a description of the function:def train_eval_and_decode(self): eval_steps = self._hparams.eval_freq_in_steps packed_dataset = "_packed" in self._hparams.problem.name mlperf_log.transformer_print(key=mlperf_log.TRAIN_LOOP) for i in range(0, self._train_spec.max_steps, eval_steps): ...
[ "Does eval and decode after training every eval_freq_in_steps." ]
Please provide a description of the function:def continuous_eval(self): for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Skip zero'th step. train_step = decoding.get_step_from_ckpt_path(ckpt_path) if train_step ...
[ "Evaluate until checkpoints stop being produced." ]
Please provide a description of the function:def continuous_eval_on_train_data(self): for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Skip zero'th step. train_step = decoding.get_step_from_ckpt_path(ckpt_path) ...
[ "Evaluate on train data until checkpoints stop being produced." ]
Please provide a description of the function:def run_std_server(self): config = tf.estimator.RunConfig() server = tf.train.Server( config.cluster_spec, job_name=config.task_type, task_index=config.task_id, protocol=config.protocol) server.join()
[ "Starts a TensorFlow server and joins the serving thread.\n\n Typically used for parameter servers.\n\n Raises:\n ValueError: if not enough information is available in the estimator's\n config to create a server.\n " ]
Please provide a description of the function:def decode(self, dataset_split=None, decode_from_file=False, checkpoint_path=None): if decode_from_file: decoding.decode_from_file(self._estimator, self._decode_hparams.decode_from_file, ...
[ "Decodes from dataset or file." ]
Please provide a description of the function:def continuous_decode(self): for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode()
[ "Decode from dataset on new checkpoint." ]
Please provide a description of the function:def continuous_decode_on_train_data(self): for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode(dataset_split=tf.estimator.ModeKeys.TRAIN)
[ "Decode from dataset on new checkpoint." ]
Please provide a description of the function:def continuous_decode_on_eval_data(self): if self._hparams.mlperf_mode: ckpt_generator = next_undecoded_checkpoint( self._hparams.model_dir, self._decode_hparams.decode_timeout_mins) else: ckpt_generator = next_checkpoint(self._hparams.mode...
[ "Decode from dataset on new checkpoint." ]
Please provide a description of the function:def continuous_decode_from_file(self): for _ in next_checkpoint(self._hparams.model_dir, self._decode_hparams.decode_timeout_mins): self.decode(decode_from_file=True)
[ "Decode from file on new checkpoint." ]
Please provide a description of the function:def _flatten_dict(original_dict): flat_dict = {} for key, value in original_dict.items(): if isinstance(value, dict): for name, tensor in value.items(): if isinstance(tensor, dict): raise ValueError("flatten_dict only handles 2 levels of ne...
[ "Flatten dict of dicts into a single dict with appropriate prefixes.\n\n Handles only 2 levels of nesting in the original dict.\n\n Args:\n original_dict: Dict which may contain one or more dicts.\n Returns:\n flat_dict: Dict without any nesting. Any dicts in the original dict have\n their keys as pre...
Please provide a description of the function:def _unflatten_dict(flat_dict, prefixes): original_dict = {} for key, value in flat_dict.items(): prefix_found = False for prefix in prefixes: full_prefix = "__" + prefix + "_" if key.startswith(full_prefix): # Add a dict to the original di...
[ "Returns a dict of dicts if any prefixes match keys in the flat dict.\n\n The function handles the case where the prefix may not be a dict.\n\n Args:\n flat_dict: A dict without any nesting.\n prefixes: A list of strings which may have been dicts in the\n original structure.\n\n " ]
Please provide a description of the function:def create_dummy_vars(): var_names = set([v.name for v in tf.global_variables()]) if "losses_avg/problem_0/total_loss:0" in var_names: return with tf.variable_scope("losses_avg"): with tf.variable_scope("problem_0"): for var_name in ["total", "extra", ...
[ "Dummy vars for restore to work when not using TPU codepath." ]
Please provide a description of the function:def create_tpu_eval_metrics_fn(problem, model_hparams): metric_fns = [] eval_metrics = problem.eval_metric_fns(model_hparams) tm = _create_target_modality(problem.get_hparams(model_hparams).modality) if isinstance(tm, dict): for k, v in six.iteritems(tm): ...
[ "Create the metrics_fn that TPUEstimatorSpec expects.", "Construct metrics dictionary." ]
Please provide a description of the function:def remove_summaries(): g = tf.get_default_graph() key = tf.GraphKeys.SUMMARIES log_debug("Remove summaries %s" % str(g.get_collection(key))) del g.get_collection_ref(key)[:] assert not g.get_collection(key)
[ "Remove summaries from the default graph." ]
Please provide a description of the function:def create_host_call(model_dir): graph = tf.get_default_graph() summaries = graph.get_collection(tf.GraphKeys.SUMMARIES) gs_t = tf.reshape(tf.to_int32(tf.train.get_global_step()), [1]) summary_kwargs = collections.OrderedDict() for t in summaries: # TODO(aid...
[ "Construct a host_call writing scalar summaries.\n\n Args:\n model_dir: String containing path to train\n\n Returns:\n (fn, args) Pair to be called by TPUEstimator as the host_call.\n ", "Training host call. Creates summaries for training metrics.\n\n Args:\n **kwargs: Dict of {str: Tensor} , wit...
Please provide a description of the function:def average_sharded_losses(sharded_losses): losses = {} for loss_name in sorted(sharded_losses[0]): all_shards = [shard_losses[loss_name] for shard_losses in sharded_losses] if isinstance(all_shards[0], tuple): sharded_num, sharded_den = zip(*all_shards)...
[ "Average losses across datashards.\n\n Args:\n sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss\n can be a single Tensor or a 2-tuple (numerator and denominator).\n\n Returns:\n losses: dict<str loss_name, Tensor avg_loss>\n " ]
Please provide a description of the function:def summarize_features(features, num_shards=1): if not common_layers.should_generate_summaries(): return with tf.name_scope("input_stats"): for (k, v) in sorted(six.iteritems(features)): if (isinstance(v, tf.Tensor) and (v.get_shape().ndims > 1) and ...
[ "Generate summaries for features." ]
Please provide a description of the function:def _compose_custom_getters(getter_a, getter_b): if not getter_a: return getter_b if not getter_b: return getter_a def getter_fn(getter, *args, **kwargs): return getter_b(functools.partial(getter_a, getter), *args, **kwargs) return getter_fn
[ "Compose two custom getters.\n\n Example use:\n tf.get_variable_scope().set_custom_getter(\n compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))\n\n This composes getters in the same way as creating a new variable scope with\n the new_getter, but it does not actually create a new varia...
Please provide a description of the function:def set_custom_getter_compose(custom_getter): tf.get_variable_scope().set_custom_getter( _compose_custom_getters(tf.get_variable_scope().custom_getter, custom_getter))
[ "Set a custom getter in the current variable scope.\n\n Do not overwrite the existing custom getter - rather compose with it.\n\n Args:\n custom_getter: a custom getter.\n " ]
Please provide a description of the function:def initialize_from_ckpt(ckpt_dir, hparams): model_dir = hparams.get("model_dir", None) already_has_ckpt = ( model_dir and tf.train.latest_checkpoint(model_dir) is not None) if already_has_ckpt: return tf.logging.info("Checkpoint dir: %s", ckpt_dir) r...
[ "Initialize variables from given directory." ]