text
stringlengths
81
112k
Bipolar ReLU as in https://arxiv.org/abs/1709.04054. def brelu(x): """Bipolar ReLU as in https://arxiv.org/abs/1709.04054.""" 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)...
Bipolar ELU as in https://arxiv.org/abs/1709.04054. def belu(x): """Bipolar ELU as in https://arxiv.org/abs/1709.04054.""" 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_s...
Gaussian Error Linear Unit. This is a smoother version of the RELU. Original paper: https://arxiv.org/abs/1606.08415 Args: x: float Tensor to perform activation. Returns: x with the GELU activation applied. def gelu(x): """Gaussian Error Linear Unit. This is a smoother version of the RELU. Or...
NAC as in https://arxiv.org/abs/1808.00508. def nac(x, depth, name=None, reuse=None): """NAC as in https://arxiv.org/abs/1808.00508.""" 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("...
NALU as in https://arxiv.org/abs/1808.00508. def nalu(x, depth, epsilon=1e-30, name=None, reuse=None): """NALU as in https://arxiv.org/abs/1808.00508.""" 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...
Argmax along with the value. def argmax_with_score(logits, axis=None): """Argmax along with the value.""" 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 ...
Compute the k-th top element of x on the last axis iteratively. This assumes values in x are non-negative, rescale if needed. It is often faster than tf.nn.top_k for small k, especially if k < 30. Note: this does not support back-propagation, it stops gradients! Args: x: a Tensor of non-negative numbers o...
find max and argmax over the last dimension. Works well on TPU Args: inputs: A tensor with shape [..., depth] Returns: values: a Tensor with shape [...] indices: a Tensor with shape [...] def top_1_tpu(inputs): """find max and argmax over the last dimension. Works well on TPU Args: inp...
Use indices to index into the last axis of x. This can be useful for recovering the actual probabilities of a sample from a probability distribution. Args: x: Tensor, n-d. indices: Tensor, (n-1)-d, where the dimension sizes match the first (n-1) dimensions of x. The values of indices will be used ...
Is this an appropriate context to generate summaries. Returns: a boolean def should_generate_summaries(): """Is this an appropriate context to generate summaries. Returns: a boolean """ name_scope = tf.contrib.framework.get_name_scope() if name_scope and "while/" in name_scope: # Summaries do...
Reshapes a to match the shape of b in all but the last dimension. def reshape_like(a, b): """Reshapes a to match the shape of b in all but the last dimension.""" 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] +...
Summarize the video using image summaries starting with prefix. def summarize_video(video, prefix, max_outputs=1): """Summarize the video using image summaries starting with prefix.""" video_shape = shape_list(video) if len(video_shape) != 5: raise ValueError("Assuming videos given as tensors in the format "...
Cast x to y's dtype, if necessary. def cast_like(x, y): """Cast x to y's dtype, if necessary.""" 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)" t...
Pad x to be even-sized on axis 1 and 2, but only if necessary. def make_even_size(x): """Pad x to be even-sized on axis 1 and 2, but only if necessary.""" 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_sha...
Loss inspired by the sliced WGAN paper: https://arxiv.org/abs/1804.01947. Puts input1 and input2 through the provided discriminator to get logits. Then, computes num_vecs random projections of the logits, sorts them on the batch dimension and returns the L2 loss between the sorted vectors. See the above-mentio...
Discriminator architecture based on InfoGAN. def deep_discriminator(x, batch_norm, is_training, filters=64, filter_size=4, stride=2, output_size=1024): """Discriminator architectu...
Instance normalization layer. def instance_norm(x): """Instance normalization layer.""" 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_ini...
Generalized convolution layer. 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, ...
Patch descriminator. def patch_discriminator(x, filters=64, filter_size=5, n=4, name="patch_discrim"): """Patch descriminator.""" 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_...
Mean and attention to reduce spatial dimensions. def mean_with_attention(x, name, num_heads=4): """Mean and attention to reduce spatial dimensions.""" 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 simple single-layer convolutional discriminator. def single_discriminator(x, filters=128, kernel_size=8, strides=4, pure_mean=False): """A simple single-layer convolutional discriminator.""" with tf.variable_scope("discriminator"): net = layers().Conv2D( filters, kernel_size,...
A convolutional discriminator with 2 layers and concatenated output. def double_discriminator(x, filters1=128, filters2=None, kernel_size=8, strides=4, pure_mean=False): """A convolutional discriminator with 2 layers and concatenated output.""" if filters2 is None: filters2 = 4 * filte...
Upscaling the image by a factor of f. def upscale(inputs, f, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR): """Upscaling the image by a factor of f.""" height, width = shape_list(inputs)[1:3] # pylint: disable=unbalanced-tuple-unpacking return tf.image.resize_images(inputs, (height * f, width * f), method)
Upsamples the given inputs. Args: net: A Tensor of size [batch_size, height, width, filters]. num_outputs: The number of output filters. stride: A list of 2 scalars or a 1x2 Tensor indicating the scale, relative to the inputs, of the output dimensions. For example, if kernel size is [2, 3], t...
Weight-level magnitude pruning. def weight_targeting(w, k): """Weight-level magnitude pruning.""" 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(tran...
Unit-level magnitude pruning. def unit_targeting(w, k): """Unit-level magnitude pruning.""" 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] ma...
Apply targeted dropout to the weights of a convolution. def td_conv(inputs, filters, kernel_size, targeting_count, targeting_fn, keep_prob, is_training, do_prune=True, strides=(1, 1), padding="valid", ...
Applies targeted dropout. Applies dropout at a rate of `1 - keep_prob` to only those elements of `inputs` marked by `targeting_fn`. See below and paper for more detail: "Targeted Dropout for Posthoc Pruning" Aidan N. Gomez, Ivan Zhang, Kevin Swersky, Yarin Gal, and Geoffrey E. Hinton. Args: inputs: T...
KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1). Args: mu: mu parameter of the distribution. log_var: log(var) parameter of the distribution. mu_p: optional mu from a learned prior distribution log_var_p: optional log(var) from a learned prior distribution Returns: the KL loss....
Convert to Tensor. def to_tensor(self): """Convert to Tensor.""" 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_...
Generate weights with normalization. def _compute_weights(self): """Generate weights with normalization.""" with tf.variable_scope("compute_weights"): self.layer.kernel = tf.nn.l2_normalize( self.layer.v, axis=self.norm_axes) * self.layer.g
Set the norm of the weight vector. def _init_norm(self, weights): """Set the norm of the weight vector.""" 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,))
Data dependent initialization for eager execution. def _data_dep_init(self, inputs): """Data dependent initialization for eager execution.""" with tf.variable_scope("data_dep_init"): # Generate data dependent init values activation = self.layer.activation self.layer.activation = None x...
Build `Layer`. def build(self, input_shape=None): """Build `Layer`.""" 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(self.laye...
Call `Layer`. def call(self, inputs): """Call `Layer`.""" # 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
Calculate mean rewards from given epoch. def compute_mean_reward(rollouts, clipped): """Calculate mean rewards from given epoch.""" 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...
Evaluate the PPO agent in the real environment. def evaluate_single_config( hparams, sampling_temp, max_num_noops, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the PPO agent in the real environment.""" tf.logging.info("Evaluating metric %s", get_metric_name( sampling_temp, max_num_no...
Evaluate the agent with multiple eval configurations. def evaluate_all_configs( hparams, agent_model_dir, eval_fn=_eval_fn_with_learner ): """Evaluate the agent with multiple eval configurations.""" metrics = {} # Iterate over all combinations of sampling temperatures and whether to do # initial no-ops. ...
Evaluate the world model (reward accuracy). def evaluate_world_model( real_env, hparams, world_model_dir, debug_video_path, split=tf.estimator.ModeKeys.EVAL, ): """Evaluate the world model (reward accuracy).""" frame_stack_size = hparams.frame_stack_size rollout_subsequences = [] def initial_frame_choo...
Write metrics to summary. def summarize_metrics(eval_metrics_writer, metrics, epoch): """Write metrics to summary.""" 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...
CamelCase game name with mode suffix. Args: short_name: snake_case name without mode e.g "crazy_climber" Returns: full game name e.g. "CrazyClimberNoFrameskip-v4" def full_game_name(short_name): """CamelCase game name with mode suffix. Args: short_name: snake_case name without mode e.g "crazy_cl...
Setup. def setup_env(hparams, batch_size, max_num_noops, rl_env_max_episode_steps=-1, env_name=None): """Setup.""" if not env_name: env_name = full_game_name(hparams.game) maxskip_envs = should_apply_max_and_skip_env(hparams) env = T2TGymEnv( ...
Copy a subset of hparams to target_hparams. def update_hparams_from_hparams(target_hparams, source_hparams, prefix): """Copy a subset of hparams to target_hparams.""" for (param_name, param_value) in six.iteritems(source_hparams.values()): if param_name.startswith(prefix): target_hparams.set_hparam(param...
Chooses a random frame sequence of given length from a set of rollouts. def random_rollout_subsequences(rollouts, num_subsequences, subsequence_length): """Chooses a random frame sequence of given length from a set of rollouts.""" def choose_subsequence(): # TODO(koz4k): Weigh rollouts by their lengths so samp...
Make frame chooser. Args: real_env: T2TEnv to take initial frames from. frame_stack_size (int): Number of consecutive frames to extract. simulation_random_starts (bool): Whether to choose frames at random. simulation_flip_first_random_for_beginning (bool): Whether to flip the first frame stack ...
Point-wise, hinge loss-like, difference between arrays. Args: arr1: integer array to compare. arr2: integer array to compare. min_diff: minimal difference taken into consideration. dtype: dtype of returned array. Returns: array def absolute_hinge_difference(arr1, arr2, min_diff=10, dtype=np.u...
Augments an observation with debug info. def augment_observation( observation, reward, cum_reward, frame_index, bar_color=None, header_height=27 ): """Augments an observation with debug info.""" img = PIL_Image().new( "RGB", (observation.shape[1], header_height,) ) draw = PIL_ImageDraw().Draw(img...
Runs a batch of rollouts from given initial observations. 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 ): """Runs a batch of rollouts from given initial observations."""...
Sets the state that will be used on next reset. def set_initial_state(self, initial_state, initial_frames): """Sets the state that will be used on next reset.""" self.env.set_initial_state(initial_state, initial_frames) self._initial_frames = initial_frames
Download corpora if necessary and unzip them. Args: tmp_dir: directory containing dataset. dataset_split: whether we're in train/dev/test mode. Returns: List of all files generated and path to file containing train/dev/test split info. def _maybe_download_corpora(tmp_dir, dataset_split): """D...
Generate splits of the data. def example_splits(url_file, all_files): """Generate splits of the data.""" def generate_hash(inp): """Generate a sha1 hash to match the raw url to the filename extracted.""" h = hashlib.sha1() h.update(inp) return h.hexdigest() all_files_map = {f.split("/")[-1]: f ...
Generate examples. def example_generator(all_files, urls_path, sum_token): """Generate examples.""" 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(ur...
Write text to files. def write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir): """Write text to files.""" def write_to_file(all_files, urls_path, tmp_dir, filename): """Write text to files.""" with io.open( os.path.join(tmp_dir, filename + ".source"), "w", encoding="utf-8"...
Infer highest epoch number from file names in data_dir. def infer_last_epoch_num(data_dir): """Infer highest epoch number from file names in 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, [...
Load T2TGymEnv with data from one epoch. Args: hparams: hparams. data_dir: data directory. which_epoch_data: data from which epoch to load. Returns: env. def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None): """Load T2TGymEnv with data from one epoch. Args: hparams: hparams...
Infer name from filenames. def infer_game_name_from_filenames(data_dir, snake_case=True): """Infer name from filenames.""" 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(...
Wrap environment with gym.Monitor. Video recording provided by Monitor requires 1) both height and width of observation to be even numbers. 2) rendering of environment Args: env: environment. video_dir: video directory. Returns: wrapped environment. def wrap_with_monitor(env, video_dir): ...
Create SimulatedEnv with minimal subset of hparams. 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 ): """"Create SimulatedEnv with minimal...
Infers standard paths to policy and model directories. Example: >>> infer_paths("/some/output/dir/", policy="", model="custom/path") {"policy": "/some/output/dir/policy", "model": "custom/path", "output_dir":"/some/output/dir/"} Args: output_dir: output directory. **subdirs: sub-directories. ...
Adds new frame to (initial) frame stack, removes last one. def add_to_initial_stack(self, frame): """Adds new frame to (initial) frame stack, removes last one.""" if not self._setable_initial_frames: raise ValueError( "This instance does not allow to manually set initial frame stack.") asse...
Add single zero row/column to observation if needed. def observation(self, frame): """Add single zero row/column to observation if needed.""" if frame.shape == self.observation_space.shape: return frame else: extended_frame = np.zeros(self.observation_space.shape, ...
Add new observation to frame stack and infer policy. Args: ob: array of shape (height, width, channels) Returns: logits and vf. def infer(self, ob): """Add new observation to frame stack and infer policy. Args: ob: array of shape (height, width, channels) Returns: logits...
Infer policy from stack of observations. Args: ob_stack: array of shape (1, frame_stack_size, height, width, channels) Returns: logits and vf. def infer_from_frame_stack(self, ob_stack): """Infer policy from stack of observations. Args: ob_stack: array of shape (1, frame_stack_size...
Normalizes the string using tokenizer.encode. Args: raw_str: the input string Returns: A string which is ready to be tokenized using split() def _normalize_string(raw_str): """Normalizes the string using tokenizer.encode. Args: raw_str: the input string Returns: A string which is ready to b...
Downloads and extracts the dataset. Args: tmp_dir: temp directory to download and extract the dataset data_dir: The base directory where data and vocab files are stored. Returns: tmp_dir: temp directory containing the raw data. def _prepare_babi_data(tmp_dir, data_dir): """Downloads and extracts th...
Parsing the bAbi dataset (train and test). Args: tmp_dir: temp directory to download and extract the dataset babi_task_id: babi task id subset: babi subset dataset_split: dataset split (train or eval) joint_training: if training the model on all tasks. Returns: babi_instances: set of trai...
It dynamically instantiates a class for each babi subsets-tasks. @registry.register_problem class BabiQaConcatAllTasks_10k(EditSequenceRegexProblem): @property def babi_task_id(self): return "qa0" @property def babi_subset(self): return "en-10k" It does not put the classes int...
Builds encoder for the given class labels. Args: data_dir: data directory Returns: An encoder for class labels. def get_labels_encoder(self, data_dir): """Builds encoder for the given class labels. Args: data_dir: data directory Returns: An encoder for class labels. ...
A generator that generates samples that are encoded. Args: data_dir: data directory tmp_dir: temp directory dataset_split: dataset split Yields: A dict. def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split): """A generator that generates samples that are encoded. ...
Return a dict for encoding and decoding inference input/output. Args: data_dir: data directory Returns: A dict of <feature name, TextEncoder>. def feature_encoders(self, data_dir): """Return a dict for encoding and decoding inference input/output. Args: data_dir: data directory ...
Returns problem_hparams. Args: defaults: default hyperparameters unused_model_hparams: model hyperparameters def hparams(self, defaults, unused_model_hparams): """Returns problem_hparams. Args: defaults: default hyperparameters unused_model_hparams: model hyperparameters """ ...
Splits of data to produce and number the output shards for each. def dataset_splits(self): """Splits of data to produce and number the output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": self.num_train_shards, }, { "split": problem.DatasetSplit.EVAL, ...
Traverses directory collecting input and target files. def _collect_data(directory, input_ext, transcription_ext): """Traverses directory collecting input and target files.""" # Directory from string to tuple pair of strings # key: the filepath to a datafile including the datafile's basename. Example, # if t...
Adding to base hparams the attributes for for librispeech. def add_librispeech_hparams(hparams): """Adding to base hparams the attributes for for librispeech.""" hparams.batch_size = 36 hparams.audio_compression = 8 hparams.hidden_size = 2048 hparams.max_input_seq_length = 600000 hparams.max_target_seq_len...
Generates linearized trees and tokens from the wsj tree format. It uses the linearized algorithm described in https://arxiv.org/abs/1412.7449. Args: tree_string: tree in wsj format Returns: tuple: (words, linearized tree) def words_and_tags_from_wsj_tree(tree_string): """Generates linearized trees a...
Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files at source_path and target_path have the same number of lines and yields dictionaries of "inputs" and "targets" where inputs and targets are token ids from source and target lines converted to integers using ...
Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files parsing_{train,dev}.trees, which contain trees in WSJ format. Args: data_dir: path to the data directory. tmp_dir: path to temporary storage directory. train: whether we're training or not. so...
Aggregate stats in per-shard stats files. def aggregate_stats(stats_files): """Aggregate stats in per-shard 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: ...
Map filename to the task id that created it assuming 1k tasks. def filename_to_task_id(fname): """Map filename to the task id that created it assuming 1k tasks.""" # This matches the order and size in WikisumBase.out_filepaths fname = os.path.basename(fname) shard_id_increment = { "train": 0, "dev"...
Validate presence and minimum size of files. def validate_data_files(problem, data_files, min_size): """Validate presence and minimum size of files.""" # 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_fil...
Set of hyperparameters. def distill_resnet_32_to_15_cifar20x5(): """Set of hyperparameters.""" 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_nes...
Downloading and preparing the dataset. Args: tmp_dir: tem directory data_dir: data directory vocab_size: size of vocabulary vocab_filename: name of vocab file def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename): """Downloading and preparing the dataset. Args: tmp_dir: t...
Gives the file paths with regards to the given split. Args: tmp_dir: temp directory split: dataset split use_control_set: uses control dataset if true. Returns: list of file paths. def get_dataset_split(tmp_dir, split, use_control_set): """Gives the file paths with regards to the given split. ...
Determine the minimum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The minimum length that a sequence can be for this dataset_split. def min_sequence_length(self, dataset_split): """Determine the minimum sequence length given a dataset_split. ...
Determine the maximum sequence length given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The maximum length that a sequence can be for this dataset_split. def max_sequence_length(self, dataset_split): """Determine the maximum sequence length given a dataset_split. ...
Determine the dataset sized given a dataset_split. Args: dataset_split: A problem.DatasetSplit. Returns: The desired number of samples for this dataset_split. def num_samples(self, dataset_split): """Determine the dataset sized given a dataset_split. Args: dataset_split: A problem....
Yields successive checkpoints from model_dir. Args: model_dir: The directory in which checkpoints are saved. timeout_mins: The maximum amount of time in minutes to wait between checkpoints. Set this to -1 to wait indefinitely. Yields: last_ckpt: a new checkpoint path, or None if the t...
Yields successive checkpoints from model_dir. def next_undecoded_checkpoint(model_dir, timeout_mins=240): """Yields successive checkpoints from model_dir.""" last_ckpt = None last_step = 0 while True: # Get the latest checkpoint. last_ckpt = tf.contrib.training.wait_for_new_checkpoint( model_di...
The TensorFlow Session config to use. 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, ...
Create RunConfig, TPUConfig, and Parallelism object. def create_run_config(model_name, master="", model_dir=None, iterations_per_loop=1000, num_shards=8, log_device_placement=False, save_...
Create a T2T Estimator. def create_estimator(model_name, hparams, run_config, schedule="train_and_evaluate", decode_hparams=None, use_tpu=False, use_tpu_estimator=False, us...
Create train and eval hooks for Experiment. 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 Experiment. 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, use_tfdbg=False, use_...
Wrapper for canonical experiment_fn. See create_experiment. def create_experiment_fn(*args, **kwargs): """Wrapper for canonical experiment_fn. See create_experiment.""" def experiment_fn(run_config, hparams): return create_experiment(run_config, hparams, *args, **kwargs) return experiment_fn
Restore from a checkpoint. def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False): """Restore from a checkpoint.""" 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...
Does eval and decode after training every eval_freq_in_steps. def train_eval_and_decode(self): """Does eval and decode after training every eval_freq_in_steps.""" eval_steps = self._hparams.eval_freq_in_steps packed_dataset = "_packed" in self._hparams.problem.name mlperf_log.transformer_print(key=mlpe...
Evaluate until checkpoints stop being produced. def continuous_eval(self): """Evaluate until checkpoints stop being produced.""" for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Skip zero'th step. train_step = decodin...
Evaluate on train data until checkpoints stop being produced. def continuous_eval_on_train_data(self): """Evaluate on train data until checkpoints stop being produced.""" for ckpt_path in next_checkpoint(self._hparams.model_dir, self._hparams.eval_timeout_mins): # Ski...
Starts a TensorFlow server and joins the serving thread. Typically used for parameter servers. Raises: ValueError: if not enough information is available in the estimator's config to create a server. def run_std_server(self): """Starts a TensorFlow server and joins the serving thread. ...
Decodes from dataset or file. def decode(self, dataset_split=None, decode_from_file=False, checkpoint_path=None): """Decodes from dataset or file.""" if decode_from_file: decoding.decode_from_file(self._estimator, self._decode_hparams...