text stringlengths 81 112k |
|---|
Context manager wrapping the training loop, updates step counters.
def training_loop(self):
"""Context manager wrapping the training loop, updates step counters."""
if not self.restarting:
self._write_counters(self._local_step_at_start, self._global_step)
tf.logging.info(
"Training %s up to ... |
Reads words from a file.
def _read_words(filename):
"""Reads words from a file."""
with tf.gfile.GFile(filename, "r") as f:
if sys.version_info[0] >= 3:
return f.read().replace("\n", " %s " % EOS).split()
else:
return f.read().decode("utf-8").replace("\n", " %s " % EOS).split() |
Reads a file to build a vocabulary of `vocab_size` most common words.
The vocabulary is sorted by occurrence count and has one word per line.
Originally from:
https://github.com/tensorflow/models/blob/master/tutorials/rnn/ptb/reader.py
Args:
filename: file to read list of words from.
vocab_path: pa... |
Reads from file and returns a `TokenTextEncoder` for the vocabulary.
def _get_token_encoder(vocab_dir, vocab_name, filename):
"""Reads from file and returns a `TokenTextEncoder` for the vocabulary."""
vocab_path = os.path.join(vocab_dir, vocab_name)
if not tf.gfile.Exists(vocab_path):
_build_vocab(filename, ... |
Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
vocab_type: which vocabulary are we using.
Returns:
The list of names of files.
def _maybe_download_corpus(tmp_dir, vocab_type):
"""Download and unpack the corpus.
Args:
tmp_dir: directory containing dataset.
vo... |
Normalize attention matrices and reshape as necessary.
def resize(att_mat, max_length=None):
"""Normalize attention matrices and reshape as necessary."""
for i, att in enumerate(att_mat):
# Add extra batch dim for viz code to work.
if att.ndim == 3:
att = np.expand_dims(att, axis=0)
if max_length... |
Compute representation of the attention ready for the d3 visualization.
Args:
inp_text: list of strings, words to be displayed on the left of the vis
out_text: list of strings, words to be displayed on the right of the vis
enc_atts: numpy array, encoder self-attentions
[num_layers, batch_size, nu... |
Decode a list of tokens to a unicode string.
Args:
tokens: a list of Unicode strings
Returns:
a unicode string
def decode(tokens):
"""Decode a list of tokens to a unicode string.
Args:
tokens: a list of Unicode strings
Returns:
a unicode string
"""
token_is_alnum = [t[0] in _ALPHANUMERI... |
Reads files matching a wildcard pattern, yielding the contents.
Args:
filepattern: A wildcard pattern matching one or more files.
max_lines: If set, stop reading after reading this many lines.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespa... |
Read the corpus and compute a dictionary of token counts.
Args:
text_filepattern: A pattern matching one or more files.
corpus_max_lines: An integer; maximum total lines to read.
split_on_newlines: A boolean. If true, then split files by lines and strip
leading and trailing whitespace from each l... |
Read a vocab file and return a dictionary of token counts.
Reads a two-column CSV file of tokens and their frequency in a dataset. The
tokens are presumed to be generated by encode() or the equivalent.
Args:
text_filepattern: A pattern matching one or more files.
max_lines: An integer; maximum total lin... |
Make a tf.train.Example for the problem.
features[input_feature_name] = input_ids
Also fills in any other required features with dummy values.
Args:
input_ids: list<int>.
problem: Problem.
input_feature_name: name of feature for input_ids.
Returns:
tf.train.Example
def _make_example(input_i... |
Wraps function to make grpc requests with runtime args.
def make_grpc_request_fn(servable_name, server, timeout_secs):
"""Wraps function to make grpc requests with runtime args."""
stub = _create_stub(server)
def _make_grpc_request(examples):
"""Builds and sends request to TensorFlow model server."""
re... |
Wraps function to make CloudML Engine requests with runtime args.
def make_cloud_mlengine_request_fn(credentials, model_name, version):
"""Wraps function to make CloudML Engine requests with runtime args."""
def _make_cloud_mlengine_request(examples):
"""Builds and sends requests to Cloud ML Engine."""
ap... |
Encodes inputs, makes request to deployed TF model, and decodes outputs.
def predict(inputs_list, problem, request_fn):
"""Encodes inputs, makes request to deployed TF model, and decodes outputs."""
assert isinstance(inputs_list, list)
fname = "inputs" if problem.has_inputs else "targets"
input_encoder = probl... |
Basic 2-frame recurrent model with stochastic tower.
def next_frame_basic_recurrent():
"""Basic 2-frame recurrent model with stochastic tower."""
hparams = basic_stochastic.next_frame_basic_stochastic_discrete()
hparams.filter_double_steps = 2
hparams.hidden_size = 64
hparams.video_num_input_frames = 4
hpa... |
Creates experiment function.
def create_teacher_experiment(run_config, hparams, argv):
"""Creates experiment function."""
tf.logging.info("training teacher")
tf.logging.set_verbosity(tf.logging.INFO)
trainer_lib.set_random_seed(FLAGS.random_seed)
usr_dir.import_usr_dir(FLAGS.t2t_usr_dir)
t2t_trainer.maybe_... |
Generate source and target data from a single file.
def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix,
source_vocab_size, target_vocab_size):
"""Generate source and target data from a single file."""
filename = "parsing_{0}.pairs".format("train" if train else "d... |
Generate source and target data from a single file.
def tabbed_parsing_character_generator(tmp_dir, train):
"""Generate source and target data from a single file."""
character_vocab = text_encoder.ByteTextEncoder()
filename = "parsing_{0}.pairs".format("train" if train else "dev")
pair_filepath = os.path.join(... |
Helper: make predictions and targets lists, check they match on length.
def _make_list(predictions, targets):
"""Helper: make predictions and targets lists, check they match on length."""
# Our models sometimes return predictions in lists, make it a list always.
# TODO(lukaszkaiser): make abstractions for neste... |
Mean of the inputs but counting only those where targets != mask_id.
def masked_mean(inputs, targets, mask_id=None):
"""Mean of the inputs but counting only those where targets != mask_id."""
inputs = [x.astype(np.float32) for x in inputs]
# We assume all elements in the list contribute equally.
# TODO(lukaszk... |
Calculate accuracy.
def accuracy(batch, model_predictions):
"""Calculate accuracy."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
correct = []
for (prediction, target) in zip(model_predictions, targets):
predicted_class = np.argmax(prediction, axis=-1)
corre... |
Calculate negative log perplexity.
def neg_log_perplexity(batch, model_predictions):
"""Calculate negative log perplexity."""
_, targets = batch
model_predictions, targets = _make_list(model_predictions, targets)
xent = []
for (prediction, target) in zip(model_predictions, targets):
hot_target = layers.o... |
Calculate loss.
def loss(params, batch, model_predict, rng):
"""Calculate loss."""
inputs, targets = batch
predictions = model_predict(inputs, params, rng=rng)
predictions, targets = _make_list(predictions, targets)
xent = []
for (pred, target) in zip(predictions, targets):
xent.append(np.sum(pred * la... |
Restore State.
def restore_state(output_dir):
"""Restore State."""
params_file = os.path.join(output_dir, "model.pkl")
if not gfile.exists(params_file):
return State(step=None, params=None, history=trax_history.History())
with gfile.GFile(params_file, "rb") as f:
(params, step, history) = pickle.load(... |
Save State and optionally gin config.
def save_state(state, output_dir, keep=False):
"""Save State and optionally gin config."""
params_file = os.path.join(output_dir, "model.pkl")
with gfile.GFile(params_file, "wb") as f:
pickle.dump((state.params, state.step, state.history), f)
if keep:
params_file =... |
Evalaute on train and eval data, and log metrics.
def evaluate_train_and_eval(step, inputs, predict_fun, eval_steps, rng,
train_sw=None, eval_sw=None, history=None):
"""Evalaute on train and eval data, and log metrics."""
step_log(step, "Evaluation")
train_metrics, eval_metrics = [
... |
Evaluate.
Args:
inputs_stream: iterable of inputs to evaluate on.
predict_fun: function from inputs to predictions. params should already be
partially applied.
metric_funs: dict from metric name to metric function, which takes inputs
and predictions and returns a scalar metric value.
rng:... |
Log metrics to summary writer and history.
def log_metrics(metrics, summ_writer, log_prefix, step, history=None):
"""Log metrics to summary writer and history."""
rjust_len = max([len(name) for name in metrics])
for name, value in six.iteritems(metrics):
step_log(step, "%s %s | % .8f" % (
log_prefix.... |
Get a JAX random number generator and set random seed everywhere.
def get_random_number_generator_and_set_seed(seed=None):
"""Get a JAX random number generator and set random seed everywhere."""
random.seed(seed)
# While python random accepts None as seed and uses time/os seed then,
# some other functions expe... |
Iterator over epochs until steps is reached. 1-indexed.
Args:
steps: int, total number of steps. Infinite if None.
epoch_steps: int, number of steps per epoch. Can also be an iterable<int> to
enable variable length epochs.
Yields:
(epoch: int, epoch id, epoch_steps: int, number of steps in this ... |
Use jit on model_predict if required.
def _jit_predict_fun(model_predict, num_devices):
"""Use jit on model_predict if required."""
def predict(x, params=(), rng=None):
"""Predict function jited and parallelized as requested."""
# On one device, jit and run.
if num_devices == 1:
return backend.ji... |
Get jit-ed update function for loss, optimizer, learning rate function.
def _jit_update_fun(predict_fun, loss_fun, optimizer, lr_fun, num_devices):
"""Get jit-ed update function for loss, optimizer, learning rate function."""
if num_devices == 1: # TODO(lukaszkaiser): remove branch when not needed.
def single... |
Reshape x into a shape [num_devices, ...].
def _reshape_by_device_single(x, num_devices):
"""Reshape x into a shape [num_devices, ...]."""
x_shape = list(x.shape)
batch_size = x_shape[0]
batch_size_per_device = batch_size // num_devices
# We require that num_devices divides batch_size evenly.
if batch_size... |
Reshape possibly nested x into a shape [num_devices, ...].
def reshape_by_device(x, num_devices):
"""Reshape possibly nested x into a shape [num_devices, ...]."""
return layers.nested_map(
x, lambda x: _reshape_by_device_single(x, num_devices)) |
Train the model on the inputs.
Args:
output_dir: Directory where to put the logs and checkpoints.
model: The model to train as a callable returning 2 callables, an init_fun
and apply_fun.
loss_fun: callable with signature: params, trax.inputs.Inputs, model, rng
-> loss.
inputs: callable r... |
Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of scalars (fan_in, fan_out).
def _compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or... |
Getter for loading from strings; returns value if can't load.
def get(identifier, value=None):
"""Getter for loading from strings; returns value if can't load."""
if value is None:
value = identifier
if identifier is None:
return None
elif isinstance(identifier, dict):
try:
return deserialize... |
Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step.
def add_time_step(self, **create_time_step_kwargs):
"""Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
... |
Replace the last time-steps with the given kwargs.
def change_last_time_step(self, **replace_time_step_kwargs):
"""Replace the last time-steps with the given kwargs."""
# Pre-conditions: self._time_steps shouldn't be empty.
assert self._time_steps
self._time_steps[-1] = self._time_steps[-1].replace(
... |
Returns a tuple of sum of raw and processed rewards.
def reward(self):
"""Returns a tuple of sum of raw and processed rewards."""
raw_rewards, processed_rewards = 0, 0
for ts in self.time_steps:
# NOTE: raw_reward and processed_reward are None for the first time-step.
if ts.raw_reward is not No... |
Completes the given trajectory at the given index.
def _complete_trajectory(self, trajectory, index):
"""Completes the given trajectory at the given index."""
assert isinstance(trajectory, Trajectory)
# This *should* be the case.
assert trajectory.last_time_step.action is None
# Add to completed... |
Resets trajectories at given indices and populates observations.
Reset can either be called right at the beginning, when there are no
time-steps, or to reset a currently active trajectory.
If resetting a currently active trajectory then we save it in
self._completed_trajectories.
Args:
indi... |
Essentially same as reset, but we don't have observations.
def complete_all_trajectories(self):
"""Essentially same as reset, but we don't have observations."""
for index in range(self.batch_size):
trajectory = self._trajectories[index]
assert trajectory.is_active
self._complete_trajectory(tr... |
Record the information obtained from taking a step in all envs.
Records (observation, rewards, done) in a new time-step and actions in the
current time-step.
If any trajectory gets done, we move that trajectory to
completed_trajectories.
Args:
observations: ndarray of first dimension self.b... |
Returns the number of time-steps in completed and incomplete trajectories.
def num_time_steps(self):
"""Returns the number of time-steps in completed and incomplete trajectories."""
num_time_steps = sum(t.num_time_steps for t in self.trajectories)
return num_time_steps + self.num_completed_time_steps |
Pads the observations in all the trajectories and returns them.
Args:
boundary: integer, Observations will be padded to (n * boundary) + 1 where
n is an integer.
Returns:
a tuple(padded_observations, time_steps), with shapes:
padded_observations: (self.batch_size, n * boundary + 1)... |
Generate squad examples.
Args:
tmp_dir: a string
dataset_split: problem.DatasetSplit.TRAIN or problem.DatasetSplit.EVAL
Yields:
dictionaries representing examples
def _generate_examples(tmp_dir, dataset_split):
"""Generate squad examples.
Args:
tmp_dir: a string
dataset_split: problem.Dat... |
Create self-attention layer based on hyperparameters.
def self_attention_layer(hparams, prefix):
"""Create self-attention layer based on hyperparameters."""
return transformer_layers.SelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
... |
Create self-attention layer based on hyperparameters.
def local_self_attention_layer(hparams, prefix):
"""Create self-attention layer based on hyperparameters."""
return transformer_layers.LocalSelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory... |
Create a layer stack based on the hyperparameter values.
def layer_stack_from_hparams(hparams, prefix):
"""Create a layer stack based on the hyperparameter values."""
layers = hparams.get(prefix + "layers")
return transformer.LayerStack(
[layers_registry[l](hparams, prefix) for l in layers],
dropout_... |
Hyperparameters for single-stack Transformer.
def mtf_unitransformer_base():
"""Hyperparameters for single-stack Transformer."""
hparams = mtf_transformer2_base()
hparams.add_hparam("autoregressive", True)
# HYPERPARAMETERS FOR THE SINGLE LAYER STACK
hparams.add_hparam("layers", ["self_att", "drd"] * 6)
# ... |
Machine translation base configuration.
def mtf_bitransformer_base():
"""Machine translation base configuration."""
hparams = mtf_transformer2_base()
hparams.max_length = 256
hparams.shared_embedding = True
# HYPERPARAMETERS FOR THE LAYER STACKS
hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6)... |
Small encoder-decoder model for testing.
def mtf_bitransformer_tiny():
"""Small encoder-decoder model for testing."""
hparams = mtf_bitransformer_base()
hparams.batch_size = 2
hparams.mesh_shape = ""
hparams.d_model = 128
hparams.encoder_layers = ["self_att", "drd"] * 2
hparams.decoder_layers = ["self_at... |
Test out all the layers on local CPU.
def mtf_unitransformer_all_layers_tiny():
"""Test out all the layers on local CPU."""
hparams = mtf_unitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.layers = ["self_att", "local_... |
Test out all the layers on local CPU.
def mtf_bitransformer_all_layers_tiny():
"""Test out all the layers on local CPU."""
hparams = mtf_bitransformer_tiny()
hparams.moe_num_experts = 4
hparams.moe_expert_x = 4
hparams.moe_expert_y = 4
hparams.moe_hidden_size = 512
hparams.encoder_layers = [
"self_... |
Series of architectures for language modeling.
We assume infinite training data, so no dropout necessary.
You can use languagemodel_wiki_noref_v32k_l1k.
(1 epoch = ~46000 steps).
TODO(noam): find a large enough dataset for these experiments.
Args:
sz: an integer
Returns:
a hparams
def mtr_lm_de... |
Model incorporating mixture-of-experts, local and global attention.
~6B parameters
32 experts in 3 hierarchichal moe layers.
Returns:
a hparams
def mtr_lm_v1():
"""Model incorporating mixture-of-experts, local and global attention.
~6B parameters
32 experts in 3 hierarchichal moe layers.
Return... |
Series of machine translation models.
All models are trained on sequences of 256 tokens.
You can use the dataset translate_enfr_wmt32k_packed.
154000 steps = 3 epochs.
Args:
sz: an integer
Returns:
a hparams
def mtr_tr_dense(sz):
"""Series of machine translation models.
All models are traine... |
With local self-attention in the decoder.
def mtr_tr_dense_local(sz):
"""With local self-attention in the decoder."""
hparams = mtr_tr_dense(sz)
hparams.decoder_layers = ["local_self_att", "enc_att", "drd"] * 6
hparams.local_attention_radius = 32
return hparams |
Recurrent decoder function.
def recurrent_transformer_decoder(
decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
name="decoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True):
"""Recurrent decoder function."""
... |
VQA attention baseline hparams.
def vqa_recurrent_self_attention_base():
"""VQA attention baseline hparams."""
hparams = universal_transformer.universal_transformer_base()
hparams.batch_size = 1024
hparams.use_fixed_batch_size = True
hparams.weight_decay = 0.
hparams.clip_grad_norm = 0.
# use default ini... |
Block of batch norm and relu.
def batch_norm_relu(inputs, is_training, relu=True):
"""Block of batch norm and relu."""
inputs = mtf.layers.batch_norm(
inputs,
is_training,
BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
init_zero=(not relu))
if relu:
inputs = mtf.relu(inputs)
re... |
Bottleneck block variant for residual networks with BN after convolutions.
Args:
inputs: a `mtf.Tensor` of shape
`[batch_dim, row_blocks, col_blocks, rows, cols, in_channels]`.
filters: `int` number of filters for the first two convolutions. Note
that the third and final convolution will use ... |
Creates one layer of blocks for the ResNet model.
Args:
inputs: `Tensor` of size `[batch, channels, height, width]`.
filters: `int` number of filters for the first convolution of the layer.
blocks: `int` number of blocks contained in the layer.
strides: `int` stride to use for the first convolution o... |
Set of hyperparameters.
def mtf_resnet_base():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.no_data_parallelism = True
hparams.use_fixed_batch_size = True
hparams.batch_size = 32
hparams.max_length = 3072
hparams.hidden_size = 256
hparams.label_smoothing = 0.0
# 8-wa... |
Catch bugs locally...
def mtf_resnet_tiny():
"""Catch bugs locally..."""
hparams = mtf_resnet_base()
hparams.num_layers = 2
hparams.hidden_size = 64
hparams.filter_size = 64
hparams.batch_size = 16
# data parallelism and model-parallelism
hparams.col_blocks = 1
hparams.mesh_shape = "batch:2"
hparam... |
Small single parameters.
def mtf_resnet_single():
"""Small single parameters."""
hparams = mtf_resnet_tiny()
hparams.mesh_shape = ""
hparams.layout = ""
hparams.hidden_size = 32
hparams.filter_size = 32
hparams.batch_size = 1
hparams.num_encoder_layers = 1
hparams.num_layers = 1
hparams.block_lengt... |
Small single parameters.
def mtf_resnet_base_single():
"""Small single parameters."""
hparams = mtf_resnet_base()
hparams.num_layers = 6
hparams.filter_size = 256
hparams.block_length = 128
hparams.mesh_shape = ""
hparams.layout = ""
return hparams |
Data parallel CIFAR parameters.
def mtf_resnet_base_cifar():
"""Data parallel CIFAR parameters."""
hparams = mtf_resnet_base()
hparams.mesh_shape = "batch:32"
hparams.layoyt = "batch:batch"
hparams.batch_size = 8
hparams.num_layers = 12
hparams.block_length = 256
hparams.hidden_size = 512
hparams.fil... |
Universal Transformer encoder function.
Prepares all the arguments and the inputs and passes it to a
universal_transformer_layer to encode the encoder_input.
Args:
encoder_input: a Tensor
encoder_self_attention_bias: bias Tensor for self-attention
(see common_attention.attention_bias())
hpara... |
Core function applying the universal transformer layer.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_unit: multi-head attention unit
pad_remover: to mask out padding in convolutional layers (efficiency).
Returns:
the output tensor, extra output (can... |
Provides the function that is used in universal transforemr steps.
Args:
x: input
hparams: model hyper-parameters
ffn_unit: feed-forward unit
attention_unit: multi-head attention unit
pad_remover: to mask out padding in convolutional layers (efficiency).
Returns:
ut_function and the ut_ini... |
Applies a feed-forward function which is parametrised for encoding.
Args:
x: input
hparams: model hyper-parameters
nonpadding_mask: optional Tensor with shape [batch_size, encoder_length]
indicating what positions are not padding. This is used
to mask out padding in convoltutional layers. We ge... |
Applies multihead attention function which is parametrised for encoding.
Args:
x: input
hparams: model hyper-parameters
encoder_self_attention_bias: a bias tensor for use in encoder self-attention
attention_dropout_broadcast_dims: Fpr noise broadcasting in the dropout
layers to save memory duri... |
Applies multihead attention function which is parametrised for decoding.
Args:
x: input (decoder input)
hparams: model hyper-parameters
encoder_output: Encoder representation. [batch_size, input_length,
hidden_dim]
decoder_self_attention_bias: Bias and mask weights for decoder
self-attent... |
Basic Universal Transformer.
This model is pretty similar to the vanilla transformer in which weights are
shared between layers. For some tasks, this simple idea brings a
generalization that is not achievable by playing with the size of the model
or drop_out parameters in the vanilla transformer.
Args:
... |
Universal Transformer with highway connection.
It transforms the state using a block contaaining sel-attention and transition
function and wrap the whole block with a highway connection.
(the new state is a combination of the state and the transformed-state
based on cary/transform gates.)
Interesting obse... |
universal_transformer with depth-wise attention.
It uses an attention mechanism-flipped vertically-
over all the states from previous steps to generate the new_state.
Args:
layer_inputs:
- state: state
- memory: contains states from all the previous steps.
step: indicating number of steps ta... |
Universal Transformer which uses a gru as transition function.
It's kind of like having a gru, filliped vertically next to the Universal
Transformer that controls the flow of the information in depth,
over different steps of the Universal Transformer.
Args:
layer_inputs:
- state: state
- input... |
Universal Transformer which uses a lstm as transition function.
It's kind of like having a lstm, filliped vertically next to the Universal
Transformer that controls the flow of the information in depth,
over different steps of the Universal Transformer.
Args:
layer_inputs:
- state: state
- in... |
ACT based models.
Implementations of all act models are based on craffel@'s cl/160711592.
(1) Basic AUT based on remainder-distribution ACT (position-wise).
(2) AUT with global halting probability (not position-wise).
(3) AUT with random halting probability (not position-wise).
(4) AUT with final state as a... |
Implements a Feed-forward layer with multiple inputs, pad-removing, etc.
Args:
inputs_list: list of input tensors
hparams: hyper-parameters
ffn_layer_type: dense / dense_dropconnect/ dense_relu_dense
name: name
kernel_initializer: kernel initializer
bias_initializer: bias initializer
acti... |
Fills the memory slot at a particular index with the given value.
Args:
memory: a 4-d tensor [memory_size, batch, length, channel] containing
the state of all steps
value: a 3-d tensor [batch, length, channel] as the sate
index: integer in [0, memory_size)
Returns:
filled memory
def fill_me... |
Add n-dimensional embedding as the depth embedding (timing signal).
Adds embeddings to represent the position of the step in the recurrent
tower.
Args:
x: a tensor with shape [max_step, batch, length, depth]
Returns:
a Tensor the same shape as x.
def add_depth_embedding(x):
"""Add n-dimensional em... |
Preprocess the input at the beginning of each step.
Args:
x: input tensor
step: step
hparams: model hyper-parameters
Returns:
preprocessed input.
def step_preprocess(x, step, hparams):
"""Preprocess the input at the beginning of each step.
Args:
x: input tensor
step: step
hparams... |
Add n-dimensional embedding as the position (horizontal) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x.
def add_position_timing_signal(x, step, hparams):
"""Add n-dimensional embedding as ... |
Add n-dimensional embedding as the step (vertical) timing signal.
Args:
x: a tensor with shape [batch, length, depth]
step: step
hparams: model hyper parameters
Returns:
a Tensor with the same shape as x.
def add_step_timing_signal(x, step, hparams):
"""Add n-dimensional embedding as the step (... |
Iterate through records in WET file object.
def wet_records_from_file_obj(f, take_ownership=False):
"""Iterate through records in WET file object."""
while True:
record = WETRecord.read(f)
if record is None:
break
if not record.url:
continue
yield record
if take_ownership:
f.c... |
Generate WETRecords from filepath.
def wet_records(wet_filepath):
"""Generate WETRecords from filepath."""
if wet_filepath.endswith('.gz'):
fopen = gzip.open
else:
fopen = tf.gfile.GFile
with fopen(wet_filepath) as f:
for record in wet_records_from_file_obj(f):
yield record |
Simple filter to remove obviously bad paragraphs (bad text extraction).
Note this needs to run very quickly as it is applied to every paragraph
in the corpus, so nothing fancy! This whole method should be linear
expected time in len(p).
Args:
p: string, paragraph
Returns:
True if we should remove t... |
Log start, end, and duration.
def timing(name=''):
"""Log start, end, and duration."""
start = datetime.datetime.now()
timestamp = start.strftime('%H:%M')
tf.logging.info('Starting job [%s] at %s', name, timestamp)
yield
end = datetime.datetime.now()
timestamp = end.strftime('%H:%M')
tf.logging.info('F... |
Read header from file. Headers end with length and then 1 blank line.
def read(cls, f):
"""Read header from file. Headers end with length and then 1 blank line."""
url = None
line = f.readline()
if not line:
# EOF
return None
while not line.startswith(cls.LENGTH_HEADER):
if line.... |
Read WETRecord from file. Records end with 2 blank lines.
def read(cls, f):
"""Read WETRecord from file. Records end with 2 blank lines."""
header = WETHeader.read(f)
if header is None:
# EOF
return None
content = f.read(header.length)
# Consume empty separators
f.readline()
f.... |
Multi-layer feed-forward neural network with non-linear activations.
def MLP(num_hidden_layers=2,
hidden_size=512,
activation_fn=layers.Relu,
num_output_classes=10,
mode="train"):
"""Multi-layer feed-forward neural network with non-linear activations."""
del mode
cur_layers = [lay... |
Verifies that all the envs have the same observation and action space.
def _verify_same_spaces(self):
"""Verifies that all the envs have the same observation and action space."""
# Pre-conditions: self._envs is initialized.
if self._envs is None:
raise ValueError("Environments not initialized.")
... |
Initializes the environments and trajectories.
Subclasses can override this if they don't want a default implementation
which initializes `batch_size` environments, but must take care to
initialize self._trajectories (this is checked in __init__ anyways).
Args:
batch_size: (int) Number of `self.... |
Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
Returns:
processed_rewards: numpy array of np.int64
def process_rewards(self, rewards):
"""Clips, rounds, and changes to integer type.
Args:
rewards: numpy array of raw (float) rewards.
... |
Returns the number of distinct rewards.
Returns:
Returns None if the reward range is infinite or the processed rewards
aren't discrete, otherwise returns the number of distinct rewards.
def num_rewards(self):
"""Returns the number of distinct rewards.
Returns:
Returns None if the reward... |
Resets environments at indices shouldn't pre-process or record.
Subclasses should override this to do the actual reset if something other
than the default implementation is desired.
Args:
indices: list of indices of underlying envs to call reset on.
Returns:
np.ndarray of stacked observat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.