INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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(transpose_w), axis=1)[:, k]
mask = ... |
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]
mask = to_float(thres >= norm)[No... |
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",
data_format="channels_last",
dilation_rate=... |
Applies targeted dropout. | def targeted_dropout(inputs,
k,
keep_prob,
targeting_fn,
is_training,
do_prune=False):
"""Applies targeted dropout.
Applies dropout at a rate of `1 - keep_prob` to only those elements of
`inputs` marked by `t... |
KL divergence of diagonal gaussian N ( mu exp ( log_var )) and N ( 0 1 ). | def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):
"""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)... |
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_shape[:-1] + [result... |
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_init = self.layer.call(inputs)
m_init, v_init... |
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.layer, "kernel"):
... |
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 frame in rollout)
rewards.append(ro... |
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_noops, clipped=False
))
eval_hparams = trainer_... |
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.
for sampling_temp in hparams.eval_sampling_temps:
#... |
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_chooser(batch_size):
assert batch_size == len... |
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.flush() |
CamelCase game name with mode suffix. | def full_game_name(short_name):
"""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"
"""
camel_game_name = misc_utils.snakecase_to_camelcase(short_name)
full_name = camel_game_name + AT... |
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(
base_env... |
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_name[len(prefix):], param_value) |
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 sampling is uniform over
# frames and not rollouts.
rollout = random.... |
Make frame chooser. | def make_initial_frame_chooser(
real_env, frame_stack_size, simulation_random_starts,
simulation_flip_first_random_for_beginning,
split=tf.estimator.ModeKeys.TRAIN,
):
"""Make frame chooser.
Args:
real_env: T2TEnv to take initial frames from.
frame_stack_size (int): Number of consecutive frames... |
Point - wise hinge loss - like difference between arrays. | def absolute_hinge_difference(arr1, arr2, min_diff=10, dtype=np.uint8):
"""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:... |
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)
draw.text(
(1, 0), "c:{:3}, r:{:... |
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."""
assert step_limit is not None or not many_rollouts_from_... |
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. | def _maybe_download_corpora(tmp_dir, dataset_split):
"""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.
... |
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 for f in all_files}
urls = ... |
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(urls_path, all_files)
... |
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") as fstory:
wit... |
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, [])
return max([int(epoch_str) for epoch_str in epochs_s... |
Load T2TGymEnv with data from one epoch. | def setup_and_load_epoch(hparams, data_dir, which_epoch_data=None):
"""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.
"""
t2t_env = rl_utils.setup_env(
hparams, batch_size=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(data_dir)
game_names = sum... |
Wrap environment with gym. Monitor. | def wrap_with_monitor(env, video_dir):
"""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 environmen... |
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 subset of hparams."""
# We need these, to initiali... |
Infers standard paths to policy and model directories. | def infer_paths(output_dir, **subdirs):
"""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... |
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.")
assert_msg = "{}, {}".format(frame.shape, self._initial_frames.s... |
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,
self.observation_space.dtype)
assert self.HW_A... |
Add new observation to frame stack and infer policy. | def infer(self, ob):
"""Add new observation to frame stack and infer policy.
Args:
ob: array of shape (height, width, channels)
Returns:
logits and vf.
"""
self._add_to_stack(ob)
logits, vf = self.infer_from_frame_stack(self._frame_stack)
return logits, vf |
Infer policy from stack of observations. | def infer_from_frame_stack(self, ob_stack):
"""Infer policy from stack of observations.
Args:
ob_stack: array of shape (1, frame_stack_size, height, width, channels)
Returns:
logits and vf.
"""
logits, vf = self.sess.run([self.logits_t, self.value_function_t],
... |
Normalizes the string using tokenizer. encode. | def _normalize_string(raw_str):
"""Normalizes the string using tokenizer.encode.
Args:
raw_str: the input string
Returns:
A string which is ready to be tokenized using split()
"""
return " ".join(
token.strip()
for token in tokenizer.encode(text_encoder.native_to_unicode(raw_str))) |
Downloads and extracts the dataset. | def _prepare_babi_data(tmp_dir, data_dir):
"""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.
"""
if not tf.gfile.Ex... |
Parsing the bAbi dataset ( train and test ). | def _babi_parser(tmp_dir,
babi_task_id,
subset,
dataset_split,
joint_training=True):
"""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: bab... |
It dynamically instantiates a class for each babi subsets - tasks. | def _register_babi_problems():
"""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... |
Builds encoder for the given 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.
"""
label_filepath = os.path.join(data_dir, self.vocab_filename)
return text_encoder.TokenTextEncoder(label_filepath) |
A generator that generates samples that are encoded. | def generate_encoded_samples(self, data_dir, tmp_dir, dataset_split):
"""A generator that generates samples that are encoded.
Args:
data_dir: data directory
tmp_dir: temp directory
dataset_split: dataset split
Yields:
A dict.
"""
generator = self.generate_samples(data_dir,... |
Return a dict for encoding and decoding inference input/ output. | def feature_encoders(self, data_dir):
"""Return a dict for encoding and decoding inference input/output.
Args:
data_dir: data directory
Returns:
A dict of <feature name, TextEncoder>.
"""
encoders = (super(BabiQa, self).feature_encoders(data_dir))
label_encoder = self.get_labels_e... |
Returns problem_hparams. | def hparams(self, defaults, unused_model_hparams):
"""Returns problem_hparams.
Args:
defaults: default hyperparameters
unused_model_hparams: model hyperparameters
"""
(super(BabiQa, self).hparams(defaults, unused_model_hparams))
p = defaults
num_classes = self._encoders["targets"].... |
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,
"shards": self.num_eval_shards,
}, {
"split": ... |
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 the datafile was "/path/to/datafile.wav" then the key wou... |
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_length = 350
hparams.max_length = hparams.max_input_seq_lengt... |
Generates linearized trees and tokens from the wsj tree format. | def words_and_tags_from_wsj_tree(tree_string):
"""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)
"""
stack, tags, words = ... |
Generator for parsing as a sequence - to - sequence task that uses tokens. | def token_generator(tree_path, source_token_vocab, target_token_vocab,
eos=None):
"""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 "ta... |
Generator for parsing as a sequence - to - sequence task that uses tokens. | def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size,
target_vocab_size):
"""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: ... |
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:
if isinstance(v, list):
all_st... |
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": 800,
"test": 900,
}
parts = fname.split("-")
split... |
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_filepaths) - set(data_files)
if missing_filepat... |
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_nesterov = True
# (base_lr... |
Downloading and preparing the dataset. | def _prepare_lambada_data(tmp_dir, data_dir, vocab_size, vocab_filename):
"""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
"""
if not tf.gfile.Exists(data_dir):
tf.gfile.MakeDi... |
Gives the file paths with regards to the given split. | def get_dataset_split(tmp_dir, split, use_control_set):
"""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.
"""
if not use_control_set:
dataset_split = {
... |
Determine the minimum sequence length given a dataset_split. | def min_sequence_length(self, dataset_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.
"""
return {
problem.DatasetSplit.TRAIN: 8,
... |
Determine the maximum sequence length given a dataset_split. | def max_sequence_length(self, 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.
"""
return {
problem.DatasetSplit.TRAIN: 64,
... |
Determine the dataset sized given a dataset_split. | def num_samples(self, 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.
"""
return {
problem.DatasetSplit.TRAIN: 1000000,
problem.DatasetSplit... |
Yields successive checkpoints from model_dir. | def next_checkpoint(model_dir, timeout_mins=240):
"""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:... |
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_dir, last_ckpt, seconds_to_sleep=60, timeout=60 *... |
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,
inter_op_parallelism_threads=0... |
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_checkpoints_steps=1000,
save_che... |
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,
use_xla=False):
"""Create... |
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_stopping_kwargs=None):
"""Create train and... |
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_dbgprofile=False,
... |
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_checkpoint_path
tf.loggin... |
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=mlperf_log.TRAIN_LOOP)
for i in range(0, self._train_spec.max_s... |
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 = decoding.get_step_from_ckpt_path(ckpt_path)
if tra... |
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):
# Skip zero'th step.
train_step = decoding.get_step_from_ckpt_... |
Starts a TensorFlow server and joins the serving thread. | def run_std_server(self):
"""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.
"""
config = tf.estimator.RunConfig()
server = tf.t... |
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.decode_from_file,
... |
Decode from dataset on new checkpoint. | def continuous_decode(self):
"""Decode from dataset on new checkpoint."""
for _ in next_checkpoint(self._hparams.model_dir,
self._decode_hparams.decode_timeout_mins):
self.decode() |
Decode from dataset on new checkpoint. | def continuous_decode_on_train_data(self):
"""Decode from dataset on new checkpoint."""
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. | def continuous_decode_on_eval_data(self):
"""Decode from dataset on new checkpoint."""
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.model... |
Decode from file on new checkpoint. | def continuous_decode_from_file(self):
"""Decode from file on new checkpoint."""
for _ in next_checkpoint(self._hparams.model_dir,
self._decode_hparams.decode_timeout_mins):
self.decode(decode_from_file=True) |
Flatten dict of dicts into a single dict with appropriate prefixes. | def _flatten_dict(original_dict):
"""Flatten dict of dicts into a single dict with appropriate prefixes.
Handles only 2 levels of nesting in the original dict.
Args:
original_dict: Dict which may contain one or more dicts.
Returns:
flat_dict: Dict without any nesting. Any dicts in the original dict ha... |
Returns a dict of dicts if any prefixes match keys in the flat dict. | def _unflatten_dict(flat_dict, prefixes):
"""Returns a dict of dicts if any prefixes match keys in the flat dict.
The function handles the case where the prefix may not be a dict.
Args:
flat_dict: A dict without any nesting.
prefixes: A list of strings which may have been dicts in the
original s... |
Dummy vars for restore to work when not using TPU codepath. | def create_dummy_vars():
"""Dummy vars for restore to work when not using TPU codepath."""
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... |
Create the metrics_fn that TPUEstimatorSpec expects. | def create_tpu_eval_metrics_fn(problem, model_hparams):
"""Create the metrics_fn that TPUEstimatorSpec expects."""
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.iter... |
Remove summaries from the default graph. | def remove_summaries():
"""Remove summaries from the default graph."""
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) |
Construct a host_call writing scalar summaries. | def create_host_call(model_dir):
"""Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
"""
graph = tf.get_default_graph()
summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
... |
Average losses across datashards. | def average_sharded_losses(sharded_losses):
"""Average losses across datashards.
Args:
sharded_losses: list<dict<str loss_name, Tensor loss>>. The loss
can be a single Tensor or a 2-tuple (numerator and denominator).
Returns:
losses: dict<str loss_name, Tensor avg_loss>
"""
losses = {}
for l... |
Generate summaries for features. | def summarize_features(features, num_shards=1):
"""Generate summaries for features."""
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
... |
Compose two custom getters. | def _compose_custom_getters(getter_a, getter_b):
"""Compose two custom getters.
Example use:
tf.get_variable_scope().set_custom_getter(
compose_custom_getters(tf.get_variable_scope().custom_getter, new_getter))
This composes getters in the same way as creating a new variable scope with
the new_getter, b... |
Set a custom getter in the current variable scope. | def set_custom_getter_compose(custom_getter):
"""Set a custom getter in the current variable scope.
Do not overwrite the existing custom getter - rather compose with it.
Args:
custom_getter: a custom getter.
"""
tf.get_variable_scope().set_custom_getter(
_compose_custom_getters(tf.get_variable_sco... |
Initialize variables from given directory. | def initialize_from_ckpt(ckpt_dir, hparams):
"""Initialize variables from given directory."""
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)
... |
Whether the target modality is real - valued. | def _target_modality_is_real(self):
"""Whether the target modality is real-valued."""
vocab_size = self._problem_hparams.vocab_size["targets"]
if vocab_size is not None and hasattr(self._hparams, "vocab_divisor"):
vocab_size += (-vocab_size) % self._hparams.vocab_divisor
modality = self._problem_h... |
Estimator model_fn sharded along batch dimension. | def model_fn_sharded(self, sharded_features):
"""Estimator model_fn sharded along batch dimension.
Args:
sharded_features: {str: [Tensor]}. Features sharded along batch dimension.
Each list is the same length (== number of shards).
Returns:
sharded_logits: [Tensor]. Logits for each sha... |
Transforms features to feed into body. | def bottom(self, features):
"""Transforms features to feed into body.
Args:
features: dict of str to Tensor. Typically it is the preprocessed data
batch after Problem's preprocess_example().
Returns:
transformed_features: dict of same key-value pairs as features. The value
Tens... |
Computes logits given body output and features. | def top(self, body_output, features):
"""Computes logits given body output and features.
Args:
body_output: dict of str to Tensor, comprising one key-value pair for each
target. Each value denotes the target's pre-logit activations.
Alternatively, it may be a single Tensor denoting the pr... |
Return a training op minimizing loss. | def optimize(self, loss, num_async_replicas=1, use_tpu=False):
"""Return a training op minimizing loss."""
lr = learning_rate.learning_rate_schedule(self.hparams)
if num_async_replicas > 1:
log_info("Dividing learning rate by num_async_replicas: %d",
num_async_replicas)
lr /= math.s... |
Set hparams with the given mode. | def set_mode(self, mode):
"""Set hparams with the given mode."""
log_info("Setting T2TModel mode to '%s'", mode)
hparams = hparams_lib.copy_hparams(self._original_hparams)
hparams.add_hparam("mode", mode)
# When not in training mode, set all forms of dropout to zero.
if mode != tf.estimator.Mode... |
Autoregressive eval. | def eval_autoregressive(self, features=None, decode_length=50):
"""Autoregressive eval.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an integer. How many additional timesteps to decode.
Returns:
logits: `Tensor`
losses: a dictio... |
A inference method. | def infer(self,
features=None,
decode_length=50,
beam_size=1,
top_beams=1,
alpha=0.0,
use_tpu=False):
"""A inference method.
Quadratic time in decode_length.
Args:
features: an map of string to `Tensor`
decode_length: an i... |
Beam search decoding. | def _beam_decode(self,
features,
decode_length,
beam_size,
top_beams,
alpha,
use_tpu=False):
"""Beam search decoding.
Models should ideally implement a more efficient version of this function.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.