text stringlengths 81 112k |
|---|
Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None.
Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being triggered.
Example: (frame, ..., frame, None, frame, ..., frame,... |
Global `cut` function that supports parallel processing.
Note that this only works using dt, custom POSTokenizer
instances are not supported.
def cut(sentence, HMM=True):
"""
Global `cut` function that supports parallel processing.
Note that this only works using dt, custom POSTokenizer
insta... |
Change the module's `cut` and `cut_for_search` functions to the
parallel version.
Note that this only works using dt, custom Tokenizer
instances are not supported.
def enable_parallel(processnum=None):
"""
Change the module's `cut` and `cut_for_search` functions to the
parallel version.
N... |
The main function that segments an entire sentence that contains
Chinese characters into separated words.
Parameter:
- sentence: The str(unicode) to be segmented.
- cut_all: Model type. True for full pattern, False for accurate pattern.
- HMM: Whether to use the Hidd... |
Finer segmentation for search engines.
def cut_for_search(self, sentence, HMM=True):
"""
Finer segmentation for search engines.
"""
words = self.cut(sentence, HMM=HMM)
for w in words:
if len(w) > 2:
for i in xrange(len(w) - 1):
gra... |
Load personalized dict to improve detect rate.
Parameter:
- f : A plain text file contains words and their ocurrences.
Can be a file-like object, or the path of the dictionary file,
whose encoding must be utf-8.
Structure of dict file:
word1 freq... |
Add a word to dictionary.
freq and tag can be omitted, freq defaults to be a calculated value
that ensures the word can be cut out.
def add_word(self, word, freq=None, tag=None):
"""
Add a word to dictionary.
freq and tag can be omitted, freq defaults to be a calculated value
... |
Suggest word frequency to force the characters in a word to be
joined or splitted.
Parameter:
- segment : The segments that the word is expected to be cut into,
If the word should be treated as a whole, use a str.
- tune : If True, tune the word frequency... |
Tokenize a sentence and yields tuples of (word, start, end)
Parameter:
- sentence: the str(unicode) to be segmented.
- mode: "default" or "search", "search" is for finer segmentation.
- HMM: whether to use the Hidden Markov Model.
def tokenize(self, unicode_sentence, mode="... |
Extract keywords from sentence using TextRank algorithm.
Parameter:
- topK: return how many top keywords. `None` for all possible words.
- withWeight: if True, return a list of (word, weight);
if False, return a list of words.
- allowPOS: the allowed... |
Extract keywords from sentence using TF-IDF algorithm.
Parameter:
- topK: return how many top keywords. `None` for all possible words.
- withWeight: if True, return a list of (word, weight);
if False, return a list of words.
- allowPOS: the allowed P... |
Generates raw (English, other) pairs from a ParaCrawl V3.0 data file.
Args:
paracrawl_file: A ParaCrawl V3.0 en-.. data file.
Yields:
Pairs of (sentence_en, sentence_xx), as Unicode strings.
Raises:
StopIteration: If the file ends while this method is in the middle of
creating a translation p... |
Generates Unicode strings, one for each <seg> in a ParaCrawl data file.
Also decodes some of the most common HTML entities found in ParaCrawl data.
Args:
paracrawl_file: A ParaCrawl V3.0 en-.. data file.
Yields:
One Unicode string for each <seg> element in the ParaCrawl data file.
def _raw_sentences(pa... |
Generates a cleaned-up stream of (English, other) translation pairs.
Cleaning includes both filtering and simplistic sentence splitting, with
minimal assumptions on the non-English pair member: (1) All filtering is
done based on the English member of the pair, and (2) sentence splitting
assumes only that sente... |
Obtain a list of image paths corresponding to training or eval case.
Args:
tmp_dir: str, the root path to which raw images were written, at the
top level having meta/ and raw/ subdirs.
case: bool, whether obtaining file paths for training (true) or eval
(false).
training_fraction: float, the ... |
Download a set of images from api.brain-map.org to `target_dir`.
Args:
image_ids: list, a list of image ids.
target_dir: str, a directory to which to download the images.
def maybe_download_image_dataset(image_ids, target_dir):
"""Download a set of images from api.brain-map.org to `target_dir`.
Args:
... |
Create a numpy array with specified shape and masked fraction.
Args:
shape: tuple, shape of the mask to create.
fraction: float, fraction of the mask area to populate with `mask_scalar`.
Returns:
numpy.array: A numpy array storing the mask.
def random_square_mask(shape, fraction):
"""Create a numpy... |
Base problem example generator for Allen Brain Atlas problems.
Args:
tmp_dir: str, a directory where raw example input data has been stored.
training: bool, whether the mode of operation is training (or,
alternatively, evaluation), determining whether examples in tmp_dir
prefixed with train or d... |
Set of hyperparameters.
def transformer_moe_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.norm_type = "layer"
hparams.hidden_size = 512
hparams.batch_size = 4096
hparams.max_length = 2001
hparams.max_input_seq_length = 2000
hparams.max_target_seq_length = 2000
... |
Hyper parameters specifics for long sequence generation.
def transformer_moe_8k():
"""Hyper parameters specifics for long sequence generation."""
hparams = transformer_moe_base()
hparams.batch_size = 8192
hparams.max_length = 0 # max_length == batch_size
hparams.eval_drop_long_sequences = True
hparams.mi... |
Base transformers model with moe.
Will have the following architecture:
* No encoder.
* Layer 0: a - sep (self-attention - unmasked separable convolutions)
* Layer 1: a - sep
* Layer 2: a - sep
* Layer 3: a - sep
* Layer 4: a - sep
* Decoder architecture:
* Layer 0: a - a - sepm (self-a... |
Model which formulate a seq2seq problem as language modeling.
def transformer_moe_prepend_8k():
"""Model which formulate a seq2seq problem as language modeling."""
hparams = transformer_moe_8k()
hparams.prepend_mode = "prepend_inputs_masked_attention"
hparams.eval_drop_long_sequences = False
hparams.max_inpu... |
Applies residual function for RevNet.
Args:
x: input tensor
depth1: Number of output channels for the first and second conv layers.
depth2: Number of output channels for the third conv layer.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
first_batch_norm: Whether to keep the first batch norm... |
Downsamples 'x' by `stride` using a 1x1 convolution filter.
Args:
x: input tensor of size [N, H, W, C]
output_channels: Desired number of output channels.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: What stride to use. Usually 1 or 2.
scope: Optional variable scope.
Returns:
... |
Downsamples 'x' by `stride` using average pooling.
Args:
x: input tensor of size [N, H, W, C]
output_channels: Desired number of output channels.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: What stride to use. Usually 1 or 2.
scope: Optional variable scope.
Returns:
A downsa... |
Standard ResNet initial block used as first RevNet block.
Args:
images: [N, H, W, 3] tensor of input images to the model.
num_channels: Output depth of convolutional layer in initial block.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
stride: stride for the convolution and pool layer.
kerne... |
Implements bottleneck RevNet unit from authors' RevNet architecture.
Args:
x1: [N, H, W, C] tensor of network activations.
x2: [N, H, W, C] tensor of network activations.
block_num: integer ID of block
depth: First depth in bottleneck residual unit.
num_layers: Number of layers in the RevNet bloc... |
Converts activations from last RevNet block to pre-logits.
Args:
x1: [NxHxWxC] tensor of network activations.
x2: [NxHxWxC] tensor of network activations.
dim: '2d' if 2-dimensional, '3d' if 3-dimensional.
training: True for train phase, False for eval phase.
scope: Optional variable scope for th... |
Uses Tensor2Tensor memory optimized RevNet block to build a RevNet.
Args:
inputs: [NxHxWx3] tensor of input images to the model.
hparams: HParams object that contains the following parameters,
in addition to the parameters contained in the basic_params1() object in
the common_hparams module:
... |
Default hparams for Revnet.
def revnet_base():
"""Default hparams for Revnet."""
hparams = common_hparams.basic_params1()
hparams.add_hparam('num_channels', [64, 128, 256, 416])
hparams.add_hparam('num_layers_per_block', [1, 1, 10, 1])
hparams.add_hparam('bottleneck', True)
hparams.add_hparam('first_batch_... |
Tiny hparams suitable for CIFAR/etc.
def revnet_cifar_base():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_base()
hparams.num_channels_init_block = 32
hparams.first_batch_norm = [False, True, True]
hparams.init_stride = 1
hparams.init_kernel_size = 3
hparams.init_maxpool = False
hparams.... |
Tiny hparams suitable for CIFAR/etc.
def revnet_110_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = False
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams |
Tiny hparams suitable for CIFAR/etc.
def revnet_164_cifar():
"""Tiny hparams suitable for CIFAR/etc."""
hparams = revnet_cifar_base()
hparams.bottleneck = True
hparams.num_channels = [16, 32, 64]
hparams.num_layers_per_block = [8, 8, 8]
return hparams |
Hyperparameters for tuning revnet.
def revnet_range(rhp):
"""Hyperparameters for tuning revnet."""
rhp.set_float('learning_rate', 0.05, 0.2, scale=rhp.LOG_SCALE)
rhp.set_float('weight_decay', 1e-5, 1e-3, scale=rhp.LOG_SCALE)
rhp.set_discrete('num_channels_init_block', [64, 128])
return rhp |
Basic 2-frame conv model.
def next_frame_basic_deterministic():
"""Basic 2-frame conv model."""
hparams = base.next_frame_base()
hparams.video_num_input_frames = 4
hparams.video_num_target_frames = 1
hparams.hidden_size = 64
hparams.batch_size = 4
hparams.num_hidden_layers = 2
hparams.optimizer = "Adaf... |
Basic 2-frame conv model with pixel noise.
def next_frame_pixel_noise():
"""Basic 2-frame conv model with pixel noise."""
hparams = next_frame_basic_deterministic()
hparams.add_hparam("video_modality_input_noise", 0.05)
hparams.bottom["inputs"] = modalities.video_pixel_noise_bottom
hparams.top["inputs"] = mo... |
Basic conv model with scheduled sampling.
def next_frame_sampling():
"""Basic conv model with scheduled sampling."""
hparams = next_frame_basic_deterministic()
hparams.scheduled_sampling_mode = "prob_inverse_exp"
hparams.scheduled_sampling_max_prob = 1.0
hparams.scheduled_sampling_decay_steps = 10000
retur... |
Conv autoencoder.
def next_frame_ae():
"""Conv autoencoder."""
hparams = next_frame_basic_deterministic()
hparams.bottom["inputs"] = modalities.video_bitwise_bottom
hparams.top["inputs"] = modalities.video_top
hparams.hidden_size = 256
hparams.batch_size = 8
hparams.num_hidden_layers = 4
hparams.num_co... |
Conv autoencoder, tiny set for testing.
def next_frame_ae_tiny():
"""Conv autoencoder, tiny set for testing."""
hparams = next_frame_tiny()
hparams.bottom["inputs"] = modalities.video_bitwise_bottom
hparams.top["inputs"] = modalities.video_top
hparams.batch_size = 8
hparams.dropout = 0.4
return hparams |
Tiny for testing.
def next_frame_tiny():
"""Tiny for testing."""
hparams = next_frame_basic_deterministic()
hparams.hidden_size = 32
hparams.num_hidden_layers = 1
hparams.num_compress_steps = 2
hparams.filter_double_steps = 1
return hparams |
Basic conv model with L1 modality.
def next_frame_l1():
"""Basic conv model with L1 modality."""
hparams = next_frame_basic_deterministic()
hparams.loss["targets"] = modalities.video_l1_loss
hparams.top["targets"] = modalities.video_l1_top
hparams.video_modality_loss_cutoff = 2.4
return hparams |
Basic conv model with L2 modality.
def next_frame_l2():
"""Basic conv model with L2 modality."""
hparams = next_frame_basic_deterministic()
hparams.loss["targets"] = modalities.video_l2_loss
hparams.top["targets"] = modalities.video_l1_top
hparams.video_modality_loss_cutoff = 2.4
return hparams |
Basic tuning grid.
def next_frame_base_range(rhp):
"""Basic tuning grid."""
rhp.set_float("dropout", 0.2, 0.6)
rhp.set_discrete("hidden_size", [64, 128, 256])
rhp.set_int("num_compress_steps", 5, 8)
rhp.set_discrete("batch_size", [4, 8, 16, 32])
rhp.set_int("num_hidden_layers", 1, 3)
rhp.set_int("filter_... |
Autoencoder world model tuning grid.
def next_frame_ae_range(rhp):
"""Autoencoder world model tuning grid."""
rhp.set_float("dropout", 0.3, 0.5)
rhp.set_int("num_compress_steps", 1, 3)
rhp.set_int("num_hidden_layers", 2, 6)
rhp.set_float("learning_rate_constant", 1., 2.)
rhp.set_float("initializer_gain", 0... |
Series of architectures for language modeling.
def mqp_lm1b_base():
"""Series of architectures for language modeling."""
hparams = mtf_transformer2.mtf_unitransformer_base()
hparams.d_model = 1024
hparams.max_length = 256
hparams.batch_size = 256
# Parameters for my_layer_stack()
hparams.num_hidden_layer... |
Initializes env_specs using the appropriate env.
def initialize_env_specs(hparams, env_problem_name):
"""Initializes env_specs using the appropriate env."""
if env_problem_name:
env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size)
else:
env = rl_utils.setup_env(hparams, hparams.bat... |
Train.
def train(hparams, output_dir, env_problem_name, report_fn=None):
"""Train."""
env_fn = initialize_env_specs(hparams, env_problem_name)
tf.logging.vlog(1, "HParams in trainer_model_free.train : %s",
misc_utils.pprint_hparams(hparams))
tf.logging.vlog(1, "Using hparams.base_algo: %s", ... |
Compute the designated learning rate factor from hparams.
def learning_rate_factor(name, step_num, hparams):
"""Compute the designated learning rate factor from hparams."""
if name == "constant":
tf.logging.info("Base learning rate: %f", hparams.learning_rate_constant)
return hparams.learning_rate_constant... |
Learning rate schedule based on hparams.
def learning_rate_schedule(hparams):
"""Learning rate schedule based on hparams."""
mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True)
mlperf_log.transformer_print(
key=mlperf_log.OPT_LR_WARMUP_STEPS,
value=hparams.learning_rate_warmup_steps)
... |
Backwards-compatible learning-rate schedule.
def legacy_learning_rate_schedule(hparams):
"""Backwards-compatible learning-rate schedule."""
step_num = _global_step(hparams)
warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps)
if hparams.learning_rate_decay_scheme == "noam":
ret = 5000.0 * hparams... |
Adjust global step if a multi-step optimizer is used.
def _global_step(hparams):
"""Adjust global step if a multi-step optimizer is used."""
step = tf.to_float(tf.train.get_or_create_global_step())
multiplier = hparams.optimizer_multistep_accumulate_steps
if not multiplier:
return step
tf.logging.info("... |
Scale learning rate according to the given schedule.
Multipliers are not cumulative.
Args:
step: global step
boundaries: List of steps to transition on.
values: Multiplier to apply at each boundary transition.
Returns:
Scaled value for the learning rate.
def _piecewise_learning_rate(step, boun... |
Learning rate decay multiplier.
def _learning_rate_decay(hparams, warmup_steps=0):
"""Learning rate decay multiplier."""
scheme = hparams.learning_rate_decay_scheme
warmup_steps = tf.to_float(warmup_steps)
global_step = _global_step(hparams)
if not scheme or scheme == "none":
return tf.constant(1.)
t... |
Learning rate warmup multiplier.
def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None):
"""Learning rate warmup multiplier."""
if not warmup_steps:
return tf.constant(1.)
tf.logging.info("Applying %s learning rate warmup for %d steps",
warmup_schedule, warmup_steps)
... |
Returns True if `find` is a subtree of `expr`.
def is_in_expr(expr, find):
"""Returns True if `find` is a subtree of `expr`."""
return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find)) |
Generate a random expression tree with a required variable.
The required variable appears exactly once in the expression.
Args:
depth: At least one leaf will be this many levels down from the top.
required_var: A char. This char is guaranteed to be placed exactly once at
a leaf somewhere in the tr... |
Generate a random expression tree.
Args:
depth: At least one leaf will be this many levels down from the top.
vlist: A list of chars. These chars are randomly selected as leaf values.
ops: A list of ExprOp instances.
Returns:
An ExprNode instance which is the root of the generated expression tree.... |
Solves for the value of the given var in an expression.
Args:
left: The root of the ExprNode tree on the left side of the equals sign.
right: The root of the ExprNode tree on the right side of the equals sign.
var: A char. The variable to solve for.
solve_ops: A dictionary with the following properti... |
Convert sympy expression into a string which can be encoded.
Args:
sympy_expr: Any sympy expression tree or string.
functions: Defines special functions. A dict mapping human readable string
names, like "log", "exp", "sin", "cos", etc., to single chars. Each
function gets a unique token, like... |
Randomly generate an algebra inverse dataset sample.
Given an input equation and variable, produce the expression equal to the
variable.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
solve_ops: S... |
Randomly generate an algebra simplify dataset sample.
Given an input expression, produce the simplified expression.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
min_depth: Expression trees will no... |
Randomly generate a symbolic integral dataset sample.
Given an input expression, produce the indefinite integral.
Args:
vlist: Variable list. List of chars that can be used in the expression.
ops: List of ExprOp instances. The allowed operators for the expression.
min_depth: Expression trees will not ... |
Initializes required objects to generate symbolic math datasets.
Produces token set, ExprOp instances, solve_op dictionary, encoders, and
decoders needed to generate the algebra inverse dataset.
Args:
alphabet_size: How many possible variables there are. Max 52.
digits: How many numerical digits to enco... |
Generate the algebra inverse dataset.
Each sample is a symbolic math equation involving unknown variables. The
task is to solve for the given variable. The target is the resulting
expression.
Args:
alphabet_size: How many possible variables there are. Max 52.
min_depth: Minimum depth of the expression... |
Generate the algebra simplify dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to simplify the expression. The target is the resulting expression.
Args:
alphabet_size: How many possible variables there are. Max 52.
min_depth: Minimum depth of the expression tre... |
Generate the calculus integrate dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to take the indefinite integral of the expression. The target is the
resulting expression.
Args:
alphabet_size: How many possible variables there are. Max 26.
min_depth: Minimum ... |
Returns True if `expr` is a subtree.
def is_in(self, expr):
"""Returns True if `expr` is a subtree."""
if expr == self:
return True
is_in_left = is_in_expr(self.left, expr)
is_in_right = is_in_expr(self.right, expr)
return is_in_left or is_in_right |
Preprocessing steps common to all models.
def preprocess_example_common(example, mode, hparams):
"""Preprocessing steps common to all models."""
if "inputs" in example and hparams.max_input_seq_length > 0:
example["inputs"] = example["inputs"][:hparams.max_input_seq_length]
if hparams.prepend_mode != "none":... |
Use input modality, vocab, and space id for target.
def _copy_problem_hparams(p_hparams):
"""Use input modality, vocab, and space id for target."""
p = p_hparams
# Duplicate input modality.
p.modality["targets"] = p.modality["inputs"]
# Duplicate input vocab size.
p.vocab_size["targets"] = p.vocab_size["in... |
Swap input/output modalities, vocab, and space ids.
def _reverse_problem_hparams(p_hparams):
"""Swap input/output modalities, vocab, and space ids."""
p = p_hparams
# Swap modalities.
# TODO(trandustin): Note this assumes target modalities have feature name
# 'target', and each intended feature to swap has ... |
A set of basic model hyperparameters.
def _default_hparams():
"""A set of basic model hyperparameters."""
return hparam.HParams(
# Use this parameter to get comparable perplexity numbers with different
# tokenizations. This value should be set to the ratio of the number of
# tokens in the test s... |
Batch size in examples per TPU core.
Args:
model_hparams: model hyperparameters
Returns:
an integer
def tpu_batch_size_per_shard(self, model_hparams):
"""Batch size in examples per TPU core.
Args:
model_hparams: model hyperparameters
Returns:
an integer
"""
if self... |
Runtime preprocessing on the whole dataset.
Return a tf.data.Datset -- the preprocessed version of the given one.
By default this function calls preprocess_example.
Args:
dataset: the Dataset of already decoded but not yet preprocessed features.
mode: tf.estimator.ModeKeys
hparams: HPara... |
Get filepattern for data files for mode.
Matches mode to a suffix.
* DatasetSplit.TRAIN: train
* DatasetSplit.EVAL: dev
* DatasetSplit.TEST: test
* tf.estimator.ModeKeys.PREDICT: dev
Args:
data_dir: str, data directory.
mode: DatasetSplit
shard: int, if provided, will only re... |
Returns problem_hparams.
def get_hparams(self, model_hparams=None):
"""Returns problem_hparams."""
if self._hparams is not None:
return self._hparams
if model_hparams is None:
model_hparams = default_model_hparams()
if self._encoders is None:
data_dir = (model_hparams and hasattr(mo... |
Reverse features between inputs and targets if the problem is '_rev'.
def maybe_reverse_features(self, feature_map):
"""Reverse features between inputs and targets if the problem is '_rev'."""
if not self._was_reversed:
return
inputs = feature_map.pop("inputs", None)
targets = feature_map.pop("ta... |
Build a Dataset for this problem.
Args:
mode: tf.estimator.ModeKeys; determines which files to read from.
data_dir: directory that contains data files.
num_threads: int, number of threads to use for decode and preprocess
Dataset.map calls.
output_buffer_size: int, how many elements ... |
Return a dict of Tensors from a serialized tensorflow.Example.
def decode_example(self, serialized_example):
"""Return a dict of Tensors from a serialized tensorflow.Example."""
data_fields, data_items_to_decoders = self.example_reading_spec()
# Necessary to rejoin examples in the correct order with the Cl... |
Retrieve dict<feature name, FeatureInfo>.
Must first call Problem.get_hparams or Problem.dataset to have the problem's
internal hparams already constructed.
Returns:
dict<feature name, FeatureInfo>
def feature_info(self):
"""Retrieve dict<feature name, FeatureInfo>.
Must first call Problem... |
Return input_fn wrapped for Estimator.
def make_estimator_input_fn(self,
mode,
hparams,
data_dir=None,
force_repeat=False,
prevent_repeat=False,
... |
Which part of the training data to read.
If there are multiple parallel calls to input_fn (multiple TPU hosts),
then we want each one to read from a separate partition of the training
data.
Args:
mode: tf.estimator.ModeKeys
config: RunConfig
params: A dict that contains parameters.
... |
Builds input pipeline for problem.
Args:
mode: tf.estimator.ModeKeys
hparams: HParams, model hparams
data_dir: str, data directory; if None, will use hparams.data_dir
params: dict, may include "batch_size"
config: RunConfig; should have the data_parallelism attribute if not using
... |
Input fn for serving export, starting from serialized example.
def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False):
"""Input fn for serving export, starting from serialized example."""
mode = tf.estimator.ModeKeys.PREDICT
serialized_example = tf.placeholder(
dtype=tf.string, sha... |
Get hyper-parameters file path.
def _get_hparams_path():
"""Get hyper-parameters file path."""
hparams_path = None
if FLAGS.output_dir:
hparams_path = os.path.join(FLAGS.output_dir, "hparams.json")
else:
tf.logging.warning(
"--output_dir not specified. Hyper-parameters will be infered from"
... |
Exports given checkpoint as tfhub module with given spec.
def export_module_spec_with_checkpoint(module_spec,
checkpoint_path,
export_path,
scope_prefix=""):
"""Exports given checkpoint as tfhub modul... |
Exports the last checkpoint from the directory as tfhub module.
It creates the Module spec and signature (based on T2T problem information),
which is later used to create and export the hub module.
Module will be saved inside the ckpt_dir.
Args:
model_name: name of the model to be exported.
hparams: T... |
Build the graph required to fetch the attention weights.
Args:
hparams_set: HParams set to build the model with.
model_name: Name of model.
data_dir: Path to directory containing training data.
problem_name: Name of problem.
beam_size: (Optional) Number of beams to use when decoding a translation... |
Get's the tensors representing the attentions from a build model.
The attentions are stored in a dict on the Transformer object while building
the graph.
Args:
translate_model: Transformer object to fetch the attention weights from.
Returns:
Tuple of attention matrices; (
enc_atts: Encoder self a... |
Input str to features dict, ready for inference.
def encode(self, input_str):
"""Input str to features dict, ready for inference."""
inputs = self.encoders["inputs"].encode(input_str) + [EOS_ID]
batch_inputs = np.reshape(inputs, [1, -1, 1, 1]) # Make it 3D.
return batch_inputs |
List of ints to str.
def decode(self, integers):
"""List of ints to str."""
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode(integers) |
List of ints to list of str.
def decode_list(self, integers):
"""List of ints to list of str."""
integers = list(np.squeeze(integers))
return self.encoders["inputs"].decode_list(integers) |
Constructs the data needed for visualizing attentions.
Args:
sess: A tf.Session object.
input_string: The input sentence to be translated and visualized.
Returns:
Tuple of (
output_string: The translated sentence.
input_list: Tokenized input sentence.
output_lis... |
Glow Hparams.
def glow_hparams():
"""Glow Hparams."""
hparams = common_hparams.basic_params1()
hparams.clip_grad_norm = None
hparams.weight_decay = 0.0
hparams.learning_rate_constant = 3e-4
hparams.batch_size = 32
# can be prev_level, prev_step or normal.
# see: glow_ops.merge_level_and_latent_dist
h... |
Shifts and pads with zero along an axis.
Example:
shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2]
shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0]
Args:
tensor: Tensor; to be shifted and padded.
shift: int; number of positions to shift by.
axis: int; along which axis to shift and pad.
Retu... |
Set of hyperparameters.
def transformer_aux_base():
"""Set of hyperparameters."""
hparams = transformer.transformer_base()
hparams.shared_embedding_and_softmax_weights = False
hparams.add_hparam("shift_values", "1,2,3,4")
return hparams |
Set of hyperparameters.
def transformer_aux_tiny():
"""Set of hyperparameters."""
hparams = transformer.transformer_tiny()
hparams.shared_embedding_and_softmax_weights = False
hparams.add_hparam("shift_values", "1,2")
return hparams |
Given frame_logits from a per-pixel softmax, generate colors.
def pixels_from_softmax(frame_logits, pure_sampling=False,
temperature=1.0, gumbel_noise_factor=0.2):
"""Given frame_logits from a per-pixel softmax, generate colors."""
# If we're purely sampling, just sample each pixel.
if pu... |
Common HParams for next_frame models.
def next_frame_base():
"""Common HParams for next_frame models."""
hparams = common_hparams.basic_params1()
# Loss cutoff.
hparams.add_hparam("video_modality_loss_cutoff", 0.01)
# Additional resizing the frames before feeding them to model.
hparams.add_hparam("preproce... |
Removes top level TimeLimit Wrapper.
Removes TimeLimit Wrapper from top level if exists, throws error if any other
TimeLimit Wrapper is present in stack.
Args:
env: environment
Returns:
the env with removed time limit wrapper.
def remove_time_limit_wrapper(env):
"""Removes top level TimeLimit Wrap... |
Wraps a gym environment. see make_gym_env for details.
def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env,
rendered_env_resize_to, sticky_actions):
"""Wraps a gym environment. see make_gym_env for details."""
# rl_env_max_episode_steps is None or int.
assert ((not rl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.