project_name
stringlengths
6
104
file_name
stringlengths
4
89
full_name
stringlengths
1
102
func_name
stringlengths
1
85
docstring
stringlengths
13
836
docstring_tokens
listlengths
4
122
code
stringlengths
23
39.7k
code_tokens
stringlengths
29
44.6k
url
int64
3
986k
devashish-patel/webcam-motion-detector
imphookapi.py
PreFindModulePathAPI.module_name
module_name
Fully-qualified name of this module.
[ "Fully-qualified", "name", "of", "this", "module." ]
def module_name(self): return self._module_name
['def', 'module_name(self):', 'return', 'self._module_name']
984,227
devashish-patel/webcam-motion-detector
imphookapi.py
PostGraphAPI.imports
imports
List of the graph nodes of all modules directly imported by this module.
[ "List", "of", "the", "graph", "nodes", "of", "all", "modules", "directly", "imported", "by", "this", "module." ]
def imports(self): return self.module_graph.flatten(start=self.module)
['def', 'imports(self):', 'return', 'self.module_graph.flatten(start=self.module)']
984,232
devashish-patel/webcam-motion-detector
dylib.py
include_library
include_library
Check if a dynamic library should be included with application or not.
[ "Check", "if", "a", "dynamic", "library", "should", "be", "included", "with", "application", "or", "not." ]
def include_library(libname): if exclude_list: if exclude_list.search(libname) and (not include_list.search(libname)): return False else: return True else: return True
['def', 'include_library(libname):', 'if', 'exclude_list:', 'if', 'exclude_list.search(libname)', 'and', '(not', 'include_list.search(libname)):', 'return', 'False', 'else:', 'return', 'True', 'else:', 'return', 'True']
984,237
devashish-patel/webcam-motion-detector
util.py
imp_walk
imp_walk
yields namepart, tuple_or_importer for each path item raise ImportError if a name can not be found.
[ "yields", "namepart,", "tuple_or_importer", "for", "each", "path", "item", "raise", "ImportError", "if", "a", "name", "can", "not", "be", "found." ]
def imp_walk(name): warnings.warn('imp_walk will be removed in a future version', DeprecationWarning) if name in sys.builtin_module_names: yield (name, (None, None, ('', '', imp.C_BUILTIN))) return paths = sys.path res = None for namepart in name.split('.'): for path_item in ...
['def', 'imp_walk(name):', "warnings.warn('imp_walk", 'will', 'be', 'removed', 'in', 'a', 'future', "version',", 'DeprecationWarning)', 'if', 'name', 'in', 'sys.builtin_module_names:', 'yield', '(name,', '(None,', 'None,', "('',", "'',", 'imp.C_BUILTIN)))', 'return', 'paths', '=', 'sys.path', 'res', '=', 'None', 'for',...
984,244
devashish-patel/webcam-motion-detector
pyimod03_importers.py
CExtensionImporter.is_package
is_package
Return always False since C extension modules are never packages.
[ "Return", "always", "False", "since", "C", "extension", "modules", "are", "never", "packages." ]
def is_package(self, fullname): return False
['def', 'is_package(self,', 'fullname):', 'return', 'False']
984,264
devashish-patel/webcam-motion-detector
pyimod03_importers.py
CExtensionImporter.get_code
get_code
Return None for a C extension module.
[ "Return", "None", "for", "a", "C", "extension", "module." ]
def get_code(self, fullname): for ext in EXTENSION_SUFFIXES: if fullname + ext in self._file_cache: return None raise ImportError('No module named ' + fullname)
['def', 'get_code(self,', 'fullname):', 'for', 'ext', 'in', 'EXTENSION_SUFFIXES:', 'if', 'fullname', '+', 'ext', 'in', 'self._file_cache:', 'return', 'None', 'raise', "ImportError('No", 'module', 'named', "'", '+', 'fullname)']
984,265
devashish-patel/webcam-motion-detector
misc.py
files_in_dir
files_in_dir
Returns a list of files which match a pattern in given directory.
[ "Returns", "a", "list", "of", "files", "which", "match", "a", "pattern", "in", "given", "directory." ]
def files_in_dir(directory, file_patterns=[]): files = [] for file_pattern in file_patterns: files.extend(glob.glob(os.path.join(directory, file_pattern))) return files
['def', 'files_in_dir(directory,', 'file_patterns=[]):', 'files', '=', '[]', 'for', 'file_pattern', 'in', 'file_patterns:', 'files.extend(glob.glob(os.path.join(directory,', 'file_pattern)))', 'return', 'files']
984,271
devashish-patel/webcam-motion-detector
misc.py
get_unicode_modules
get_unicode_modules
Try importing codecs and encodings to include unicode support in created binary.
[ "Try", "importing", "codecs", "and", "encodings", "to", "include", "unicode", "support", "in", "created", "binary." ]
def get_unicode_modules(): modules = [] try: import codecs modules.append('codecs') except ImportError: logger.error("Cannot detect modules 'codecs'.") return modules
['def', 'get_unicode_modules():', 'modules', '=', '[]', 'try:', 'import', 'codecs', "modules.append('codecs')", 'except', 'ImportError:', 'logger.error("Cannot', 'detect', 'modules', '\'codecs\'.")', 'return', 'modules']
984,272
devashish-patel/webcam-motion-detector
winutils.py
get_system_path
get_system_path
Return the path that Windows will search for dlls.
[ "Return", "the", "path", "that", "Windows", "will", "search", "for", "dlls." ]
def get_system_path(): from ... import compat _bpath = [] sys_dir = compat.win32api.GetSystemDirectory() _bpath = [sys_dir, get_windows_dir()] _bpath.extend(compat.getenv('PATH', '').split(os.pathsep)) return _bpath
['def', 'get_system_path():', 'from', '...', 'import', 'compat', '_bpath', '=', '[]', 'sys_dir', '=', 'compat.win32api.GetSystemDirectory()', '_bpath', '=', '[sys_dir,', 'get_windows_dir()]', "_bpath.extend(compat.getenv('PATH',", "'').split(os.pathsep))", 'return', '_bpath']
984,330
AxelGoetz/website-fingerprinting
helpers.py
shuffle_data
shuffle_data
Shuffles an array-like object, we perform it in here to reset the seed and get consistent shuffles.
[ "Shuffles", "an", "array-like", "object,", "we", "perform", "it", "in", "here", "to", "reset", "the", "seed", "and", "get", "consistent", "shuffles." ]
def shuffle_data(data, seed=123): np.random.seed(seed) np.random.shuffle(data)
['def', 'shuffle_data(data,', 'seed=123):', 'np.random.seed(seed)', 'np.random.shuffle(data)']
985,683
wkostuch/wild-style
gatys_method.py
vgg_layers
vgg_layers
Creates a VGG model that returns a list of intermediate output values.
[ "Creates", "a", "VGG", "model", "that", "returns", "a", "list", "of", "intermediate", "output", "values." ]
def vgg_layers(layer_names): vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet') vgg.trainable = False outputs = [vgg.get_layer(name).output for name in layer_names] model = tf.keras.Model([vgg.input], outputs) return model
['def', 'vgg_layers(layer_names):', 'vgg', '=', 'tf.keras.applications.VGG19(include_top=False,', "weights='imagenet')", 'vgg.trainable', '=', 'False', 'outputs', '=', '[vgg.get_layer(name).output', 'for', 'name', 'in', 'layer_names]', 'model', '=', 'tf.keras.Model([vgg.input],', 'outputs)', 'return', 'model']
985,845
wkostuch/wild-style
gatys_method.py
clip_0_1
clip_0_1
Clips the values in a tensor to be between 0 and 1.
[ "Clips", "the", "values", "in", "a", "tensor", "to", "be", "between", "0", "and", "1." ]
def clip_0_1(image): return tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=1.0)
['def', 'clip_0_1(image):', 'return', 'tf.clip_by_value(image,', 'clip_value_min=0.0,', 'clip_value_max=1.0)']
985,847
wkostuch/wild-style
gatys_method.py
GatysNeuralStyleTransfer.show_content_image
show_content_image
Displays the content image using the system's default photo viewer.
[ "Displays", "the", "content", "image", "using", "the", "system's", "default", "photo", "viewer." ]
def show_content_image(self): meth.display_tensor_as_image(self.content_image_tensor)
['def', 'show_content_image(self):', 'meth.display_tensor_as_image(self.content_image_tensor)']
985,849
wkostuch/wild-style
gatys_method.py
GatysNeuralStyleTransfer.show_style_image
show_style_image
Displays the style image using the system's default photo viewer.
[ "Displays", "the", "style", "image", "using", "the", "system's", "default", "photo", "viewer." ]
def show_style_image(self): meth.display_tensor_as_image(self.style_image_tensor)
['def', 'show_style_image(self):', 'meth.display_tensor_as_image(self.style_image_tensor)']
985,850
wkostuch/wild-style
gatys_method.py
GatysNeuralStyleTransfer.style_step
style_step
Styles the image one increment.
[ "Styles", "the", "image", "one", "increment." ]
def style_step(self): image = self.transfer_image_tensor with tf.GradientTape() as tape: outputs = self.extractor(image) loss = self.style_content_loss(outputs) loss += self.total_variation_weight * tf.image.total_variation(image) grad = tape.gradient(loss, image) self.optimizer....
['def', 'style_step(self):', 'image', '=', 'self.transfer_image_tensor', 'with', 'tf.GradientTape()', 'as', 'tape:', 'outputs', '=', 'self.extractor(image)', 'loss', '=', 'self.style_content_loss(outputs)', 'loss', '+=', 'self.total_variation_weight', '*', 'tf.image.total_variation(image)', 'grad', '=', 'tape.gradient(...
985,851
wkostuch/wild-style
gatys_method.py
GatysNeuralStyleTransfer.style_content_loss
style_content_loss
Returns the total loss for style transferral.
[ "Returns", "the", "total", "loss", "for", "style", "transferral." ]
def style_content_loss(self, outputs): style_outputs = outputs['style'] content_outputs = outputs['content'] style_loss = tf.add_n([tf.reduce_mean((style_outputs[name] - self.style_targets[name]) ** 2) for name in style_outputs.keys()]) style_loss *= self.style_weight / len(self.style_layers) conten...
['def', 'style_content_loss(self,', 'outputs):', 'style_outputs', '=', "outputs['style']", 'content_outputs', '=', "outputs['content']", 'style_loss', '=', 'tf.add_n([tf.reduce_mean((style_outputs[name]', '-', 'self.style_targets[name])', '**', '2)', 'for', 'name', 'in', 'style_outputs.keys()])', 'style_loss', '*=', 's...
985,853
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
basic_stochastic.py
NextFrameBasicStochasticDiscrete.inject_latent
inject_latent
Inject a deterministic latent based on the target frame.
[ "Inject", "a", "deterministic", "latent", "based", "on", "the", "target", "frame." ]
def inject_latent(self, layer, features, filters): del filters hparams = self.hparams final_filters = common_layers.shape_list(layer)[-1] filters = hparams.hidden_size kernel = (4, 4) if hparams.mode == tf.estimator.ModeKeys.PREDICT: layer_shape = common_layers.shape_list(layer) ...
['def', 'inject_latent(self,', 'layer,', 'features,', 'filters):', 'del', 'filters', 'hparams', '=', 'self.hparams', 'final_filters', '=', 'common_layers.shape_list(layer)[-1]', 'filters', '=', 'hparams.hidden_size', 'kernel', '=', '(4,', '4)', 'if', 'hparams.mode', '==', 'tf.estimator.ModeKeys.PREDICT:', 'layer_shape'...
965,951
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
emily.py
NextFrameEmily.encoder
encoder
VGG based image encoder.
[ "VGG", "based", "image", "encoder." ]
def encoder(self, inputs, nout): vgg_layer = common_video.vgg_layer net01 = inputs net11 = tfcl.repeat(net01, 2, vgg_layer, 64, scope='h1', is_training=self.is_training) net12 = tfl.max_pooling2d(net11, [2, 2], strides=(2, 2), name='h1_pool') net21 = tfcl.repeat(net12, 2, vgg_layer, 128, scope='h2',...
['def', 'encoder(self,', 'inputs,', 'nout):', 'vgg_layer', '=', 'common_video.vgg_layer', 'net01', '=', 'inputs', 'net11', '=', 'tfcl.repeat(net01,', '2,', 'vgg_layer,', '64,', "scope='h1',", 'is_training=self.is_training)', 'net12', '=', 'tfl.max_pooling2d(net11,', '[2,', '2],', 'strides=(2,', '2),', "name='h1_pool')"...
965,952
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
emily.py
NextFrameEmily.decoder
decoder
VGG based image decoder.
[ "VGG", "based", "image", "decoder." ]
def decoder(self, inputs, skips, nout): vgg_layer = common_video.vgg_layer net = inputs net = tfl.conv2d_transpose(net, 512, kernel_size=4, padding='VALID', name='d1_deconv', activation=None) net = tfl.batch_normalization(net, training=self.is_training, name='d1_bn') net = tf.nn.leaky_relu(net) ...
['def', 'decoder(self,', 'inputs,', 'skips,', 'nout):', 'vgg_layer', '=', 'common_video.vgg_layer', 'net', '=', 'inputs', 'net', '=', 'tfl.conv2d_transpose(net,', '512,', 'kernel_size=4,', "padding='VALID',", "name='d1_deconv',", 'activation=None)', 'net', '=', 'tfl.batch_normalization(net,', 'training=self.is_training...
965,953
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
emily.py
NextFrameEmily.stacked_lstm
stacked_lstm
Stacked LSTM layers with FC layers as input and output embeddings.
[ "Stacked", "LSTM", "layers", "with", "FC", "layers", "as", "input", "and", "output", "embeddings." ]
def stacked_lstm(self, inputs, states, hidden_size, output_size, nlayers): net = inputs net = tfl.dense(net, hidden_size, activation=None, name='af1') for i in range(nlayers): (net, states[i]) = common_video.basic_lstm(net, states[i], hidden_size, name='alstm%d' % i) net = tfl.dense(net, output_...
['def', 'stacked_lstm(self,', 'inputs,', 'states,', 'hidden_size,', 'output_size,', 'nlayers):', 'net', '=', 'inputs', 'net', '=', 'tfl.dense(net,', 'hidden_size,', 'activation=None,', "name='af1')", 'for', 'i', 'in', 'range(nlayers):', '(net,', 'states[i])', '=', 'common_video.basic_lstm(net,', 'states[i],', 'hidden_s...
965,954
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
emily.py
NextFrameEmily.lstm_gaussian
lstm_gaussian
Stacked LSTM layers with FC layer as input and gaussian as output.
[ "Stacked", "LSTM", "layers", "with", "FC", "layer", "as", "input", "and", "gaussian", "as", "output." ]
def lstm_gaussian(self, inputs, states, hidden_size, output_size, nlayers): net = inputs net = tfl.dense(net, hidden_size, activation=None, name='bf1') for i in range(nlayers): (net, states[i]) = common_video.basic_lstm(net, states[i], hidden_size, name='blstm%d' % i) mu = tfl.dense(net, output_...
['def', 'lstm_gaussian(self,', 'inputs,', 'states,', 'hidden_size,', 'output_size,', 'nlayers):', 'net', '=', 'inputs', 'net', '=', 'tfl.dense(net,', 'hidden_size,', 'activation=None,', "name='bf1')", 'for', 'i', 'in', 'range(nlayers):', '(net,', 'states[i])', '=', 'common_video.basic_lstm(net,', 'states[i],', 'hidden_...
965,955
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
savp.py
NextFrameSAVP.encoder
encoder
COnvnet that encodes inputs into mean and std of a gaussian.
[ "COnvnet", "that", "encodes", "inputs", "into", "mean", "and", "std", "of", "a", "gaussian." ]
def encoder(self, inputs, n_layers=3): latent_dims = self.hparams.z_dim shape_as_list = inputs.shape.as_list() if len(shape_as_list) != 5: raise ValueError('Expected inputs to be a 5-D, got %d' % len(shape_as_list)) if inputs.dtype != tf.float32: raise ValueError('Expected dtype tf.float...
['def', 'encoder(self,', 'inputs,', 'n_layers=3):', 'latent_dims', '=', 'self.hparams.z_dim', 'shape_as_list', '=', 'inputs.shape.as_list()', 'if', 'len(shape_as_list)', '!=', '5:', 'raise', "ValueError('Expected", 'inputs', 'to', 'be', 'a', '5-D,', 'got', "%d'", '%', 'len(shape_as_list))', 'if', 'inputs.dtype', '!=', ...
965,957
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
savp.py
NextFrameSAVP.get_fc_dimensions
get_fc_dimensions
Get expected fully connected shape after a series of convolutions.
[ "Get", "expected", "fully", "connected", "shape", "after", "a", "series", "of", "convolutions." ]
def get_fc_dimensions(self, strides, kernel_sizes): (output_height, output_width, _) = self.hparams.problem.frame_shape output_steps = self.hparams.video_num_target_frames output_shape = np.array([output_steps, output_height, output_width]) for (curr_stride, kernel_size) in zip(strides, kernel_sizes): ...
['def', 'get_fc_dimensions(self,', 'strides,', 'kernel_sizes):', '(output_height,', 'output_width,', '_)', '=', 'self.hparams.problem.frame_shape', 'output_steps', '=', 'self.hparams.video_num_target_frames', 'output_shape', '=', 'np.array([output_steps,', 'output_height,', 'output_width])', 'for', '(curr_stride,', 'ke...
965,958
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
savp.py
NextFrameSAVP.g_step
g_step
Performs the generator step in computing the GAN loss.
[ "Performs", "the", "generator", "step", "in", "computing", "the", "GAN", "loss." ]
def g_step(self, gen_frames, fake_logits_stop): hparam_to_gen_loss = {'least_squares': gan_losses.least_squares_generator_loss, 'cross_entropy': gan_losses.modified_generator_loss, 'wasserstein': gan_losses.wasserstein_generator_loss} fake_logits = self.discriminator(gen_frames) mean_fake_logits = tf.reduce...
['def', 'g_step(self,', 'gen_frames,', 'fake_logits_stop):', 'hparam_to_gen_loss', '=', "{'least_squares':", 'gan_losses.least_squares_generator_loss,', "'cross_entropy':", 'gan_losses.modified_generator_loss,', "'wasserstein':", 'gan_losses.wasserstein_generator_loss}', 'fake_logits', '=', 'self.discriminator(gen_fram...
965,960
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
savp.py
NextFrameSAVP.pad_conv3d_lrelu
pad_conv3d_lrelu
Pad, apply 3-D convolution and leaky relu.
[ "Pad,", "apply", "3-D", "convolution", "and", "leaky", "relu." ]
def pad_conv3d_lrelu(self, activations, n_filters, kernel_size, strides, scope): padding = [[0, 0], [1, 1], [1, 1], [1, 1], [0, 0]] if isinstance(strides, numbers.Integral): strides = [strides] * 3 strides = [1] + strides + [1] filter_shape = [kernel_size] * 3 + activations.shape[-1:].as_list() ...
['def', 'pad_conv3d_lrelu(self,', 'activations,', 'n_filters,', 'kernel_size,', 'strides,', 'scope):', 'padding', '=', '[[0,', '0],', '[1,', '1],', '[1,', '1],', '[1,', '1],', '[0,', '0]]', 'if', 'isinstance(strides,', 'numbers.Integral):', 'strides', '=', '[strides]', '*', '3', 'strides', '=', '[1]', '+', 'strides', '...
965,962
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
savp.py
NextFrameSAVP.construct_model
construct_model
Model that takes in images and returns predictions.
[ "Model", "that", "takes", "in", "images", "and", "returns", "predictions." ]
def construct_model(self, images, actions, rewards): if not self.hparams.use_vae and (not self.hparams.use_gan): raise ValueError('Set at least one of use_vae or use_gan to be True') if self.hparams.gan_optimization not in ['joint', 'sequential']: raise ValueError('self.hparams.gan_optimization ...
['def', 'construct_model(self,', 'images,', 'actions,', 'rewards):', 'if', 'not', 'self.hparams.use_vae', 'and', '(not', 'self.hparams.use_gan):', 'raise', "ValueError('Set", 'at', 'least', 'one', 'of', 'use_vae', 'or', 'use_gan', 'to', 'be', "True')", 'if', 'self.hparams.gan_optimization', 'not', 'in', "['joint',", "'...
965,963
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
sv2p.py
NextFrameSv2p.get_scheduled_sample_func
get_scheduled_sample_func
Creates a function for scheduled sampling based on given hparams.
[ "Creates", "a", "function", "for", "scheduled", "sampling", "based", "on", "given", "hparams." ]
def get_scheduled_sample_func(self, batch_size): with tf.variable_scope('scheduled_sampling_func', reuse=False): iter_num = self.get_iteration_num() if self.hparams.scheduled_sampling_mode == 'prob': decay_steps = self.hparams.scheduled_sampling_decay_steps probability = tf.t...
['def', 'get_scheduled_sample_func(self,', 'batch_size):', 'with', "tf.variable_scope('scheduled_sampling_func',", 'reuse=False):', 'iter_num', '=', 'self.get_iteration_num()', 'if', 'self.hparams.scheduled_sampling_mode', '==', "'prob':", 'decay_steps', '=', 'self.hparams.scheduled_sampling_decay_steps', 'probability'...
965,964
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
sv2p.py
NextFrameSv2p.reward_prediction
reward_prediction
Builds a reward prediction network.
[ "Builds", "a", "reward", "prediction", "network." ]
def reward_prediction(self, input_images, input_reward, action, latent): conv_size = self.tinyify([32, 32, 16, 8]) with tf.variable_scope('reward_pred', reuse=tf.AUTO_REUSE): x = tf.concat(input_images, axis=3) x = tfcl.layer_norm(x) x = tfl.conv2d(x, conv_size[1], [3, 3], strides=(2, 2)...
['def', 'reward_prediction(self,', 'input_images,', 'input_reward,', 'action,', 'latent):', 'conv_size', '=', 'self.tinyify([32,', '32,', '16,', '8])', 'with', "tf.variable_scope('reward_pred',", 'reuse=tf.AUTO_REUSE):', 'x', '=', 'tf.concat(input_images,', 'axis=3)', 'x', '=', 'tfcl.layer_norm(x)', 'x', '=', 'tfl.conv...
965,966
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
sv2p.py
NextFrameSv2p.construct_model
construct_model
Build convolutional lstm video predictor using CDNA, or DNA.
[ "Build", "convolutional", "lstm", "video", "predictor", "using", "CDNA,", "or", "DNA." ]
def construct_model(self, images, actions, rewards): context_frames = self.hparams.video_num_input_frames buffer_size = self.hparams.reward_prediction_buffer_size if buffer_size == 0: buffer_size = context_frames if buffer_size > context_frames: raise ValueError('Buffer size is bigger th...
['def', 'construct_model(self,', 'images,', 'actions,', 'rewards):', 'context_frames', '=', 'self.hparams.video_num_input_frames', 'buffer_size', '=', 'self.hparams.reward_prediction_buffer_size', 'if', 'buffer_size', '==', '0:', 'buffer_size', '=', 'context_frames', 'if', 'buffer_size', '>', 'context_frames:', 'raise'...
965,967
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
sv2p.py
NextFrameSv2p.get_extra_loss
get_extra_loss
Losses in addition to the default modality losses.
[ "Losses", "in", "addition", "to", "the", "default", "modality", "losses." ]
def get_extra_loss(self, latent_means=None, latent_stds=None, true_frames=None, gen_frames=None, beta=1.0): del true_frames del gen_frames kl_loss = 0.0 if self.is_training: for (i, (mean, std)) in enumerate(zip(latent_means, latent_stds)): kl_loss += common_layers.kl_divergence(mean...
['def', 'get_extra_loss(self,', 'latent_means=None,', 'latent_stds=None,', 'true_frames=None,', 'gen_frames=None,', 'beta=1.0):', 'del', 'true_frames', 'del', 'gen_frames', 'kl_loss', '=', '0.0', 'if', 'self.is_training:', 'for', '(i,', '(mean,', 'std))', 'in', 'enumerate(zip(latent_means,', 'latent_stds)):', 'kl_loss'...
965,968
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
sv2p_params.py
next_frame_sv2p_atari
next_frame_sv2p_atari
SV2P model for atari.
[ "SV2P", "model", "for", "atari." ]
def next_frame_sv2p_atari(): hparams = next_frame_sv2p() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 4 hparams.concatenate_actions = False hparams.num_iterations_1st_stage = 15000 hparams.num_iterations_2nd_stage = 15000 hparams.latent_loss_multiplier_schedule = 'noi...
['def', 'next_frame_sv2p_atari():', 'hparams', '=', 'next_frame_sv2p()', 'hparams.video_num_input_frames', '=', '4', 'hparams.video_num_target_frames', '=', '4', 'hparams.concatenate_actions', '=', 'False', 'hparams.num_iterations_1st_stage', '=', '15000', 'hparams.num_iterations_2nd_stage', '=', '15000', 'hparams.late...
965,970
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
sv2p_params.py
next_frame_sv2p_cutoff
next_frame_sv2p_cutoff
SV2P model with additional cutoff in L2 loss for environments like pong.
[ "SV2P", "model", "with", "additional", "cutoff", "in", "L2", "loss", "for", "environments", "like", "pong." ]
def next_frame_sv2p_cutoff(): hparams = next_frame_sv2p() hparams.video_modality_loss_cutoff = 0.4 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 return hparams
['def', 'next_frame_sv2p_cutoff():', 'hparams', '=', 'next_frame_sv2p()', 'hparams.video_modality_loss_cutoff', '=', '0.4', 'hparams.video_num_input_frames', '=', '4', 'hparams.video_num_target_frames', '=', '1', 'return', 'hparams']
965,971
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
rl_trainer_lib.py
define_train
define_train
Define the training setup.
[ "Define", "the", "training", "setup." ]
def define_train(hparams): with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): (memory, collect_summary, initialization) = collect.define_collect(hparams, 'ppo_train', eval_phase=False) ppo_summary = ppo.define_ppo_epoch(memory, hparams) summary = tf.summary.merge([collect_...
['def', 'define_train(hparams):', 'with', 'tf.variable_scope(tf.get_variable_scope(),', 'reuse=tf.AUTO_REUSE):', '(memory,', 'collect_summary,', 'initialization)', '=', 'collect.define_collect(hparams,', "'ppo_train',", 'eval_phase=False)', 'ppo_summary', '=', 'ppo.define_ppo_epoch(memory,', 'hparams)', 'summary', '=',...
965,972
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
make_relative_timing_fn
make_relative_timing_fn
Make a function that logs the duration since it was made.
[ "Make", "a", "function", "that", "logs", "the", "duration", "since", "it", "was", "made." ]
def make_relative_timing_fn(): start_time = time.time() def format_relative_time(): time_delta = time.time() - start_time return str(datetime.timedelta(seconds=time_delta)) def log_relative_time(): tf.logging.info('Timing: %s', format_relative_time()) return log_relative_time
['def', 'make_relative_timing_fn():', 'start_time', '=', 'time.time()', 'def', 'format_relative_time():', 'time_delta', '=', 'time.time()', '-', 'start_time', 'return', 'str(datetime.timedelta(seconds=time_delta))', 'def', 'log_relative_time():', "tf.logging.info('Timing:", "%s',", 'format_relative_time())', 'return', ...
965,973
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
generate_real_env_data
generate_real_env_data
Run the agent against the real environment and return mean reward.
[ "Run", "the", "agent", "against", "the", "real", "environment", "and", "return", "mean", "reward." ]
def generate_real_env_data(problem_name, agent_policy_path, hparams, data_dir, tmp_dir, autoencoder_path=None, eval_phase=False): tf.gfile.MakeDirs(data_dir) with temporary_flags({'problem': problem_name, 'agent_policy_path': agent_policy_path, 'autoencoder_path': autoencoder_path}): gym_problem = regis...
['def', 'generate_real_env_data(problem_name,', 'agent_policy_path,', 'hparams,', 'data_dir,', 'tmp_dir,', 'autoencoder_path=None,', 'eval_phase=False):', 'tf.gfile.MakeDirs(data_dir)', 'with', "temporary_flags({'problem':", 'problem_name,', "'agent_policy_path':", 'agent_policy_path,', "'autoencoder_path':", 'autoenco...
965,974
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
train_autoencoder
train_autoencoder
Train autoencoder on problem_name.
[ "Train", "autoencoder", "on", "problem_name." ]
def train_autoencoder(problem_name, data_dir, output_dir, hparams, epoch): train_steps = hparams.autoencoder_train_steps * (epoch + 2) with temporary_flags({'problem': problem_name, 'data_dir': data_dir, 'output_dir': output_dir, 'model': 'autoencoder_ordered_discrete', 'hparams_set': 'autoencoder_discrete_pong...
['def', 'train_autoencoder(problem_name,', 'data_dir,', 'output_dir,', 'hparams,', 'epoch):', 'train_steps', '=', 'hparams.autoencoder_train_steps', '*', '(epoch', '+', '2)', 'with', "temporary_flags({'problem':", 'problem_name,', "'data_dir':", 'data_dir,', "'output_dir':", 'output_dir,', "'model':", "'autoencoder_ord...
965,975
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
train_agent_real_env
train_agent_real_env
Train the PPO agent in the real environment.
[ "Train", "the", "PPO", "agent", "in", "the", "real", "environment." ]
def train_agent_real_env(problem_name, agent_model_dir, event_dir, world_model_dir, epoch_data_dir, hparams, epoch=0, is_final_epoch=False): del epoch, is_final_epoch gym_problem = registry.problem(problem_name) ppo_hparams = trainer_lib.create_hparams(hparams.ppo_params) ppo_params_names = ['epochs_num...
['def', 'train_agent_real_env(problem_name,', 'agent_model_dir,', 'event_dir,', 'world_model_dir,', 'epoch_data_dir,', 'hparams,', 'epoch=0,', 'is_final_epoch=False):', 'del', 'epoch,', 'is_final_epoch', 'gym_problem', '=', 'registry.problem(problem_name)', 'ppo_hparams', '=', 'trainer_lib.create_hparams(hparams.ppo_pa...
965,977
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
evaluate_world_model
evaluate_world_model
Generate simulated environment data and return reward accuracy.
[ "Generate", "simulated", "environment", "data", "and", "return", "reward", "accuracy." ]
def evaluate_world_model(simulated_problem_name, problem_name, hparams, world_model_dir, epoch_data_dir, tmp_dir): gym_simulated_problem = registry.problem(simulated_problem_name) sim_steps = hparams.simulated_env_generator_num_steps gym_simulated_problem.settable_num_steps = sim_steps with temporary_fl...
['def', 'evaluate_world_model(simulated_problem_name,', 'problem_name,', 'hparams,', 'world_model_dir,', 'epoch_data_dir,', 'tmp_dir):', 'gym_simulated_problem', '=', 'registry.problem(simulated_problem_name)', 'sim_steps', '=', 'hparams.simulated_env_generator_num_steps', 'gym_simulated_problem.settable_num_steps', '=...
965,978
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
encode_dataset
encode_dataset
Encode all frames in dataset with model and write them out to out_files.
[ "Encode", "all", "frames", "in", "dataset", "with", "model", "and", "write", "them", "out", "to", "out_files." ]
def encode_dataset(model, dataset, problem, ae_hparams, autoencoder_path, out_files): batch_size = 8 dataset = dataset.batch(batch_size) examples = dataset.make_one_shot_iterator().get_next() images = examples.pop('frame') images = tf.expand_dims(images, 1) encoded = model.encode(images) enc...
['def', 'encode_dataset(model,', 'dataset,', 'problem,', 'ae_hparams,', 'autoencoder_path,', 'out_files):', 'batch_size', '=', '8', 'dataset', '=', 'dataset.batch(batch_size)', 'examples', '=', 'dataset.make_one_shot_iterator().get_next()', 'images', '=', "examples.pop('frame')", 'images', '=', 'tf.expand_dims(images,'...
965,980
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_base_quick
rl_modelrl_base_quick
Base setting but quicker with only 2 epochs.
[ "Base", "setting", "but", "quicker", "with", "only", "2", "epochs." ]
def rl_modelrl_base_quick(): hparams = rl_modelrl_base() hparams.epochs = 2 hparams.ppo_epochs_num = 1000 hparams.ppo_epoch_length = 50 hparams.real_ppo_epochs_num = 10 return hparams
['def', 'rl_modelrl_base_quick():', 'hparams', '=', 'rl_modelrl_base()', 'hparams.epochs', '=', '2', 'hparams.ppo_epochs_num', '=', '1000', 'hparams.ppo_epoch_length', '=', '50', 'hparams.real_ppo_epochs_num', '=', '10', 'return', 'hparams']
965,984
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_base_quick_sd
rl_modelrl_base_quick_sd
Quick setting with stochastic discrete model.
[ "Quick", "setting", "with", "stochastic", "discrete", "model." ]
def rl_modelrl_base_quick_sd(): hparams = rl_modelrl_base_quick() hparams.generative_model = 'next_frame_basic_stochastic_discrete' hparams.generative_model_params = 'next_frame_basic_stochastic_discrete' return hparams
['def', 'rl_modelrl_base_quick_sd():', 'hparams', '=', 'rl_modelrl_base_quick()', 'hparams.generative_model', '=', "'next_frame_basic_stochastic_discrete'", 'hparams.generative_model_params', '=', "'next_frame_basic_stochastic_discrete'", 'return', 'hparams']
965,985
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_base_quick_sm
rl_modelrl_base_quick_sm
Quick setting with sampling.
[ "Quick", "setting", "with", "sampling." ]
def rl_modelrl_base_quick_sm(): hparams = rl_modelrl_base_quick() hparams.generative_model_params = 'next_frame_sampling' return hparams
['def', 'rl_modelrl_base_quick_sm():', 'hparams', '=', 'rl_modelrl_base_quick()', 'hparams.generative_model_params', '=', "'next_frame_sampling'", 'return', 'hparams']
965,986
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_base_sv2p
rl_modelrl_base_sv2p
Base setting with sv2p as world model.
[ "Base", "setting", "with", "sv2p", "as", "world", "model." ]
def rl_modelrl_base_sv2p(): hparams = rl_modelrl_base() hparams.generative_model = 'next_frame_sv2p' hparams.generative_model_params = 'next_frame_sv2p_atari' return hparams
['def', 'rl_modelrl_base_sv2p():', 'hparams', '=', 'rl_modelrl_base()', 'hparams.generative_model', '=', "'next_frame_sv2p'", 'hparams.generative_model_params', '=', "'next_frame_sv2p_atari'", 'return', 'hparams']
965,988
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_medium
rl_modelrl_medium
Small set for larger testing.
[ "Small", "set", "for", "larger", "testing." ]
def rl_modelrl_medium(): hparams = rl_modelrl_base() hparams.num_real_env_frames //= 2 return hparams
['def', 'rl_modelrl_medium():', 'hparams', '=', 'rl_modelrl_base()', 'hparams.num_real_env_frames', '//=', '2', 'return', 'hparams']
965,990
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_tiny
rl_modelrl_tiny
Tiny set for testing.
[ "Tiny", "set", "for", "testing." ]
def rl_modelrl_tiny(): return rl_modelrl_base_sampling().override_from_dict(tf.contrib.training.HParams(epochs=1, num_real_env_frames=128, simulated_env_generator_num_steps=64, model_train_steps=2, ppo_epochs_num=2, ppo_time_limit=5, ppo_epoch_length=5, ppo_num_agents=2, real_ppo_epochs_num=1, real_ppo_epoch_length...
['def', 'rl_modelrl_tiny():', 'return', 'rl_modelrl_base_sampling().override_from_dict(tf.contrib.training.HParams(epochs=1,', 'num_real_env_frames=128,', 'simulated_env_generator_num_steps=64,', 'model_train_steps=2,', 'ppo_epochs_num=2,', 'ppo_time_limit=5,', 'ppo_epoch_length=5,', 'ppo_num_agents=2,', 'real_ppo_epoc...
965,993
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l1_medium
rl_modelrl_l1_medium
Medium parameter set with L1 loss.
[ "Medium", "parameter", "set", "with", "L1", "loss." ]
def rl_modelrl_l1_medium(): hparams = rl_modelrl_medium() hparams.generative_model_params = 'next_frame_l1' return hparams
['def', 'rl_modelrl_l1_medium():', 'hparams', '=', 'rl_modelrl_medium()', 'hparams.generative_model_params', '=', "'next_frame_l1'", 'return', 'hparams']
965,997
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l1_short
rl_modelrl_l1_short
Short parameter set with L1 loss.
[ "Short", "parameter", "set", "with", "L1", "loss." ]
def rl_modelrl_l1_short(): hparams = rl_modelrl_short() hparams.generative_model_params = 'next_frame_l1' return hparams
['def', 'rl_modelrl_l1_short():', 'hparams', '=', 'rl_modelrl_short()', 'hparams.generative_model_params', '=', "'next_frame_l1'", 'return', 'hparams']
965,998
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l1_tiny
rl_modelrl_l1_tiny
Tiny parameter set with L1 loss.
[ "Tiny", "parameter", "set", "with", "L1", "loss." ]
def rl_modelrl_l1_tiny(): hparams = rl_modelrl_tiny() hparams.generative_model_params = 'next_frame_l1' return hparams
['def', 'rl_modelrl_l1_tiny():', 'hparams', '=', 'rl_modelrl_tiny()', 'hparams.generative_model_params', '=', "'next_frame_l1'", 'return', 'hparams']
965,999
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l2_base
rl_modelrl_l2_base
Parameter set with L2 loss.
[ "Parameter", "set", "with", "L2", "loss." ]
def rl_modelrl_l2_base(): hparams = rl_modelrl_base() hparams.generative_model_params = 'next_frame_l2' return hparams
['def', 'rl_modelrl_l2_base():', 'hparams', '=', 'rl_modelrl_base()', 'hparams.generative_model_params', '=', "'next_frame_l2'", 'return', 'hparams']
966,000
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l2_medium
rl_modelrl_l2_medium
Medium parameter set with L2 loss.
[ "Medium", "parameter", "set", "with", "L2", "loss." ]
def rl_modelrl_l2_medium(): hparams = rl_modelrl_medium() hparams.generative_model_params = 'next_frame_l2' return hparams
['def', 'rl_modelrl_l2_medium():', 'hparams', '=', 'rl_modelrl_medium()', 'hparams.generative_model_params', '=', "'next_frame_l2'", 'return', 'hparams']
966,001
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l2_short
rl_modelrl_l2_short
Short parameter set with L2 loss.
[ "Short", "parameter", "set", "with", "L2", "loss." ]
def rl_modelrl_l2_short(): hparams = rl_modelrl_short() hparams.generative_model_params = 'next_frame_l2' return hparams
['def', 'rl_modelrl_l2_short():', 'hparams', '=', 'rl_modelrl_short()', 'hparams.generative_model_params', '=', "'next_frame_l2'", 'return', 'hparams']
966,002
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l2_tiny
rl_modelrl_l2_tiny
Tiny parameter set with L2 loss.
[ "Tiny", "parameter", "set", "with", "L2", "loss." ]
def rl_modelrl_l2_tiny(): hparams = rl_modelrl_tiny() hparams.generative_model_params = 'next_frame_l2' return hparams
['def', 'rl_modelrl_l2_tiny():', 'hparams', '=', 'rl_modelrl_tiny()', 'hparams.generative_model_params', '=', "'next_frame_l2'", 'return', 'hparams']
966,003
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_ae_base
rl_modelrl_ae_base
Parameter set for autoencoders.
[ "Parameter", "set", "for", "autoencoders." ]
def rl_modelrl_ae_base(): hparams = rl_modelrl_base() hparams.ppo_params = 'ppo_pong_ae_base' hparams.generative_model_params = 'next_frame_ae' hparams.autoencoder_train_steps = 50000 return hparams
['def', 'rl_modelrl_ae_base():', 'hparams', '=', 'rl_modelrl_base()', 'hparams.ppo_params', '=', "'ppo_pong_ae_base'", 'hparams.generative_model_params', '=', "'next_frame_ae'", 'hparams.autoencoder_train_steps', '=', '50000', 'return', 'hparams']
966,004
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_ae_l1_base
rl_modelrl_ae_l1_base
Parameter set for autoencoders and L1 loss.
[ "Parameter", "set", "for", "autoencoders", "and", "L1", "loss." ]
def rl_modelrl_ae_l1_base(): hparams = rl_modelrl_ae_base() hparams.generative_model_params = 'next_frame_l1' return hparams
['def', 'rl_modelrl_ae_l1_base():', 'hparams', '=', 'rl_modelrl_ae_base()', 'hparams.generative_model_params', '=', "'next_frame_l1'", 'return', 'hparams']
966,005
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_ae_l2_base
rl_modelrl_ae_l2_base
Parameter set for autoencoders and L2 loss.
[ "Parameter", "set", "for", "autoencoders", "and", "L2", "loss." ]
def rl_modelrl_ae_l2_base(): hparams = rl_modelrl_ae_base() hparams.generative_model_params = 'next_frame_l2' return hparams
['def', 'rl_modelrl_ae_l2_base():', 'hparams', '=', 'rl_modelrl_ae_base()', 'hparams.generative_model_params', '=', "'next_frame_l2'", 'return', 'hparams']
966,006
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_l1l2cutoff_range
rl_modelrl_l1l2cutoff_range
Loss and loss-cutoff tuning grid.
[ "Loss", "and", "loss-cutoff", "tuning", "grid." ]
def rl_modelrl_l1l2cutoff_range(rhp): rhp.set_float('model.video_modality_loss_cutoff', 1.4, 3.4)
['def', 'rl_modelrl_l1l2cutoff_range(rhp):', "rhp.set_float('model.video_modality_loss_cutoff',", '1.4,', '3.4)']
966,011
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_dummy_range
rl_modelrl_dummy_range
Dummy tuning grid just to get the variance.
[ "Dummy", "tuning", "grid", "just", "to", "get", "the", "variance." ]
def rl_modelrl_dummy_range(rhp): rhp.set_float('model.moe_loss_coef', 0.01, 0.02)
['def', 'rl_modelrl_dummy_range(rhp):', "rhp.set_float('model.moe_loss_coef',", '0.01,', '0.02)']
966,014
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
split_scoped_hparams
split_scoped_hparams
Split single HParams with scoped keys into multiple.
[ "Split", "single", "HParams", "with", "scoped", "keys", "into", "multiple." ]
def split_scoped_hparams(scopes, merged_hparams): split_values = dict([(scope, dict()) for scope in scopes]) merged_values = merged_hparams.values() for (scoped_key, value) in six.iteritems(merged_values): scope = scoped_key.split('.')[0] key = scoped_key[len(scope) + 1:] split_value...
['def', 'split_scoped_hparams(scopes,', 'merged_hparams):', 'split_values', '=', 'dict([(scope,', 'dict())', 'for', 'scope', 'in', 'scopes])', 'merged_values', '=', 'merged_hparams.values()', 'for', '(scoped_key,', 'value)', 'in', 'six.iteritems(merged_values):', 'scope', '=', "scoped_key.split('.')[0]", 'key', '=', 's...
966,016
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
training_loop_hparams_from_scoped_overrides
training_loop_hparams_from_scoped_overrides
Create HParams suitable for training loop from scoped HParams.
[ "Create", "HParams", "suitable", "for", "training", "loop", "from", "scoped", "HParams." ]
def training_loop_hparams_from_scoped_overrides(scoped_overrides, trial_id): trial_hp_overrides = scoped_overrides.values() loop_hp = create_loop_hparams() model_hp_name = trial_hp_overrides.get('loop.generative_model_params', loop_hp.generative_model_params) model_hp = registry.hparams(model_hp_name).p...
['def', 'training_loop_hparams_from_scoped_overrides(scoped_overrides,', 'trial_id):', 'trial_hp_overrides', '=', 'scoped_overrides.values()', 'loop_hp', '=', 'create_loop_hparams()', 'model_hp_name', '=', "trial_hp_overrides.get('loop.generative_model_params',", 'loop_hp.generative_model_params)', 'model_hp', '=', 're...
966,017
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
simulated_batch_env.py
compute_uncertainty_reward
compute_uncertainty_reward
Uncertainty reward based on logits.
[ "Uncertainty", "reward", "based", "on", "logits." ]
def compute_uncertainty_reward(logits, predictions): vocab_size = logits.shape[-1] assert vocab_size > 1 log_probs = common_layers.log_prob_from_logits(logits) max_log_probs = common_layers.index_last_dim_with_indices(log_probs, predictions) neg_log_prob = tf.nn.relu(-max_log_probs - 0.02) reduc...
['def', 'compute_uncertainty_reward(logits,', 'predictions):', 'vocab_size', '=', 'logits.shape[-1]', 'assert', 'vocab_size', '>', '1', 'log_probs', '=', 'common_layers.log_prob_from_logits(logits)', 'max_log_probs', '=', 'common_layers.index_last_dim_with_indices(log_probs,', 'predictions)', 'neg_log_prob', '=', 'tf.n...
966,031
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
utils.py
get_observation_space
get_observation_space
Get observation space associated with environment spec.
[ "Get", "observation", "space", "associated", "with", "environment", "spec." ]
def get_observation_space(environment_spec): return environment_spec.env_lambda().observation_space
['def', 'get_observation_space(environment_spec):', 'return', 'environment_spec.env_lambda().observation_space']
966,037
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
utils.py
get_action_space
get_action_space
Get action space associated with environment spec.
[ "Get", "action", "space", "associated", "with", "environment", "spec." ]
def get_action_space(environment_spec): return environment_spec.env_lambda().action_space
['def', 'get_action_space(environment_spec):', 'return', 'environment_spec.env_lambda().action_space']
966,038
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
utils.py
parse_dtype
parse_dtype
Get a tensor dtype from a OpenAI Gym space.
[ "Get", "a", "tensor", "dtype", "from", "a", "OpenAI", "Gym", "space." ]
def parse_dtype(space): if isinstance(space, gym.spaces.Discrete): return tf.int32 if isinstance(space, gym.spaces.Box): return tf.as_dtype(space.dtype) raise NotImplementedError()
['def', 'parse_dtype(space):', 'if', 'isinstance(space,', 'gym.spaces.Discrete):', 'return', 'tf.int32', 'if', 'isinstance(space,', 'gym.spaces.Box):', 'return', 'tf.as_dtype(space.dtype)', 'raise', 'NotImplementedError()']
966,041
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
serving_utils.py
make_grpc_request_fn
make_grpc_request_fn
Wraps function to make grpc requests with runtime args.
[ "Wraps", "function", "to", "make", "grpc", "requests", "with", "runtime", "args." ]
def make_grpc_request_fn(servable_name, server, timeout_secs): stub = _create_stub(server) def _make_grpc_request(examples): request = predict_pb2.PredictRequest() request.model_spec.name = servable_name request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto([ex.SerializeToS...
['def', 'make_grpc_request_fn(servable_name,', 'server,', 'timeout_secs):', 'stub', '=', '_create_stub(server)', 'def', '_make_grpc_request(examples):', 'request', '=', 'predict_pb2.PredictRequest()', 'request.model_spec.name', '=', 'servable_name', "request.inputs['input'].CopyFrom(tf.contrib.util.make_tensor_proto([e...
966,044
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
serving_utils.py
predict
predict
Encodes inputs, makes request to deployed TF model, and decodes outputs.
[ "Encodes", "inputs,", "makes", "request", "to", "deployed", "TF", "model,", "and", "decodes", "outputs." ]
def predict(inputs_list, problem, request_fn): assert isinstance(inputs_list, list) fname = 'inputs' if problem.has_inputs else 'targets' input_encoder = problem.feature_info[fname].encoder input_ids_list = [_encode(inputs, input_encoder, add_eos=problem.has_inputs) for inputs in inputs_list] exampl...
['def', 'predict(inputs_list,', 'problem,', 'request_fn):', 'assert', 'isinstance(inputs_list,', 'list)', 'fname', '=', "'inputs'", 'if', 'problem.has_inputs', 'else', "'targets'", 'input_encoder', '=', 'problem.feature_info[fname].encoder', 'input_ids_list', '=', '[_encode(inputs,', 'input_encoder,', 'add_eos=problem....
966,046
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
cloud_mlengine.py
get_default_master_type
get_default_master_type
Returns master_type for trainingInput.
[ "Returns", "master_type", "for", "trainingInput." ]
def get_default_master_type(num_gpus=1): gpus_to_master_map = {0: 'standard', 1: 'standard_p100', 4: 'complex_model_m_p100', 8: 'complex_model_l_gpu'} if num_gpus not in gpus_to_master_map: raise ValueError('Num gpus must be in %s' % str(sorted(list(gpus_to_master_map.keys())))) return gpus_to_maste...
['def', 'get_default_master_type(num_gpus=1):', 'gpus_to_master_map', '=', '{0:', "'standard',", '1:', "'standard_p100',", '4:', "'complex_model_m_p100',", '8:', "'complex_model_l_gpu'}", 'if', 'num_gpus', 'not', 'in', 'gpus_to_master_map:', 'raise', "ValueError('Num", 'gpus', 'must', 'be', 'in', "%s'", '%', 'str(sorte...
966,059
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
cloud_mlengine.py
configure_job
configure_job
Construct jobSpec for ML Engine job.
[ "Construct", "jobSpec", "for", "ML", "Engine", "job." ]
def configure_job(): training_input = {'pythonModule': 'tensor2tensor.bin.t2t_trainer', 'args': flags_as_args(), 'region': text_encoder.native_to_unicode(default_region()), 'runtimeVersion': RUNTIME_VERSION, 'pythonVersion': '3.5' if sys.version_info.major == 3 else '2.7', 'jobDir': FLAGS.output_dir, 'scaleTier': '...
['def', 'configure_job():', 'training_input', '=', "{'pythonModule':", "'tensor2tensor.bin.t2t_trainer',", "'args':", 'flags_as_args(),', "'region':", 'text_encoder.native_to_unicode(default_region()),', "'runtimeVersion':", 'RUNTIME_VERSION,', "'pythonVersion':", "'3.5'", 'if', 'sys.version_info.major', '==', '3', 'el...
966,060
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
cloud_mlengine.py
launch_job
launch_job
Launch job on ML Engine.
[ "Launch", "job", "on", "ML", "Engine." ]
def launch_job(job_spec): project_id = 'projects/{}'.format(text_encoder.native_to_unicode(default_project())) credentials = GoogleCredentials.get_application_default() cloudml = discovery.build('ml', 'v1', credentials=credentials, cache_discovery=False) request = cloudml.projects().jobs().create(body=j...
['def', 'launch_job(job_spec):', 'project_id', '=', "'projects/{}'.format(text_encoder.native_to_unicode(default_project()))", 'credentials', '=', 'GoogleCredentials.get_application_default()', 'cloudml', '=', "discovery.build('ml',", "'v1',", 'credentials=credentials,', 'cache_discovery=False)', 'request', '=', 'cloud...
966,061
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
cloud_mlengine.py
tar_and_copy_t2t
tar_and_copy_t2t
Tar Tensor2Tensor and cp to train_dir.
[ "Tar", "Tensor2Tensor", "and", "cp", "to", "train_dir." ]
def tar_and_copy_t2t(train_dir): tf.logging.info('Tarring and pushing local Tensor2Tensor package.') output = text_encoder.native_to_unicode(shell_output('pip show tensor2tensor')).split('\n') assert output[1].startswith('Version') assert output[7].startswith('Location') t2t_version = output[1].spli...
['def', 'tar_and_copy_t2t(train_dir):', "tf.logging.info('Tarring", 'and', 'pushing', 'local', 'Tensor2Tensor', "package.')", 'output', '=', "text_encoder.native_to_unicode(shell_output('pip", 'show', "tensor2tensor')).split('\\n')", 'assert', "output[1].startswith('Version')", 'assert', "output[7].startswith('Location...
966,062
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
decoding.py
decode_from_dataset
decode_from_dataset
Perform decoding from dataset.
[ "Perform", "decoding", "from", "dataset." ]
def decode_from_dataset(estimator, problem_name, hparams, decode_hp, decode_to_file=None, dataset_split=None, checkpoint_path=None): tf.logging.info('Performing local inference from dataset for %s.', str(problem_name)) shard = decode_hp.shard_id if decode_hp.shards > 1 else None output_dir = os.path.join(es...
['def', 'decode_from_dataset(estimator,', 'problem_name,', 'hparams,', 'decode_hp,', 'decode_to_file=None,', 'dataset_split=None,', 'checkpoint_path=None):', "tf.logging.info('Performing", 'local', 'inference', 'from', 'dataset', 'for', "%s.',", 'str(problem_name))', 'shard', '=', 'decode_hp.shard_id', 'if', 'decode_hp...
966,067
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
decoding.py
show_and_save_image
show_and_save_image
Shows an image using matplotlib and saves it.
[ "Shows", "an", "image", "using", "matplotlib", "and", "saves", "it." ]
def show_and_save_image(img, save_path): try: import matplotlib.pyplot as plt except ImportError as e: tf.logging.warning('Showing and saving an image requires matplotlib to be installed: %s', e) raise NotImplementedError('Image display and save not implemented.') plt.imshow(img) ...
['def', 'show_and_save_image(img,', 'save_path):', 'try:', 'import', 'matplotlib.pyplot', 'as', 'plt', 'except', 'ImportError', 'as', 'e:', "tf.logging.warning('Showing", 'and', 'saving', 'an', 'image', 'requires', 'matplotlib', 'to', 'be', 'installed:', "%s',", 'e)', 'raise', "NotImplementedError('Image", 'display', '...
966,071
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
decoding.py
run_postdecode_hooks
run_postdecode_hooks
Run hooks after decodes have run.
[ "Run", "hooks", "after", "decodes", "have", "run." ]
def run_postdecode_hooks(decode_hook_args, dataset_split): hooks = decode_hook_args.problem.decode_hooks if not hooks: return global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir) if global_step is None: tf.logging.info('Skipping decode hooks because no checkpoint ye...
['def', 'run_postdecode_hooks(decode_hook_args,', 'dataset_split):', 'hooks', '=', 'decode_hook_args.problem.decode_hooks', 'if', 'not', 'hooks:', 'return', 'global_step', '=', 'latest_checkpoint_step(decode_hook_args.estimator.model_dir)', 'if', 'global_step', 'is', 'None:', "tf.logging.info('Skipping", 'decode', 'hoo...
966,072
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
expert_utils.py
distributed_moe
distributed_moe
Call a distributed mixture of experts.
[ "Call", "a", "distributed", "mixture", "of", "experts." ]
def distributed_moe(data_parallelism, expert_devices, xs, train, input_size, expert_fn, num_experts, k=2, loss_coef=0.01, name=None): dp = data_parallelism ep = Parallelism([expert_devices[i % len(expert_devices)] for i in range(num_experts)], reuse=None) xs_flat = dp(tf.reshape, xs, [[-1, input_size]] * dp...
['def', 'distributed_moe(data_parallelism,', 'expert_devices,', 'xs,', 'train,', 'input_size,', 'expert_fn,', 'num_experts,', 'k=2,', 'loss_coef=0.01,', 'name=None):', 'dp', '=', 'data_parallelism', 'ep', '=', 'Parallelism([expert_devices[i', '%', 'len(expert_devices)]', 'for', 'i', 'in', 'range(num_experts)],', 'reuse...
966,087
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
learning_rate.py
learning_rate_schedule
learning_rate_schedule
Learning rate schedule based on hparams.
[ "Learning", "rate", "schedule", "based", "on", "hparams." ]
def learning_rate_schedule(hparams): step_num = _global_step(hparams) schedule_string = hparams.learning_rate_schedule names = schedule_string.split('*') names = [name.strip() for name in names if name.strip()] ret = tf.constant(1.0) for name in names: ret *= learning_rate_factor(name, s...
['def', 'learning_rate_schedule(hparams):', 'step_num', '=', '_global_step(hparams)', 'schedule_string', '=', 'hparams.learning_rate_schedule', 'names', '=', "schedule_string.split('*')", 'names', '=', '[name.strip()', 'for', 'name', 'in', 'names', 'if', 'name.strip()]', 'ret', '=', 'tf.constant(1.0)', 'for', 'name', '...
966,108
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
metrics.py
image_rmse
image_rmse
RMSE but will argmax if last dim is not 1.
[ "RMSE", "but", "will", "argmax", "if", "last", "dim", "is", "not", "1." ]
def image_rmse(predictions, labels, weights_fn=common_layers.weights_all): if common_layers.shape_list(predictions)[-1] == 1: predictions = tf.squeeze(predictions, axis=[-1]) else: predictions = tf.argmax(predictions, axis=-1) return padded_rmse(predictions, labels, weights_fn)
['def', 'image_rmse(predictions,', 'labels,', 'weights_fn=common_layers.weights_all):', 'if', 'common_layers.shape_list(predictions)[-1]', '==', '1:', 'predictions', '=', 'tf.squeeze(predictions,', 'axis=[-1])', 'else:', 'predictions', '=', 'tf.argmax(predictions,', 'axis=-1)', 'return', 'padded_rmse(predictions,', 'la...
966,109
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
metrics.py
rounding_sequence_accuracy
rounding_sequence_accuracy
Sequence accuracy for L1/L2 losses: round down the predictions to ints.
[ "Sequence", "accuracy", "for", "L1/L2", "losses:", "round", "down", "the", "predictions", "to", "ints." ]
def rounding_sequence_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): outputs = tf.squeeze(tf.to_int32(predictions), axis=-1) weights = weights_fn(labels) labels = tf.to_int32(labels) not_correct = tf.to_float(tf.not_equal(outputs, labels)) * weights axis = list(range(1, len...
['def', 'rounding_sequence_accuracy(predictions,', 'labels,', 'weights_fn=common_layers.weights_nonzero):', 'outputs', '=', 'tf.squeeze(tf.to_int32(predictions),', 'axis=-1)', 'weights', '=', 'weights_fn(labels)', 'labels', '=', 'tf.to_int32(labels)', 'not_correct', '=', 'tf.to_float(tf.not_equal(outputs,', 'labels))',...
966,112
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
metrics.py
rounding_accuracy
rounding_accuracy
Rounding accuracy for L1/L2 losses: round down the predictions to ints.
[ "Rounding", "accuracy", "for", "L1/L2", "losses:", "round", "down", "the", "predictions", "to", "ints." ]
def rounding_accuracy(predictions, labels, weights_fn=common_layers.weights_nonzero): outputs = tf.squeeze(tf.to_int32(predictions)) labels = tf.squeeze(labels) weights = weights_fn(labels) labels = tf.to_int32(labels) return (tf.to_float(tf.equal(outputs, labels)), weights)
['def', 'rounding_accuracy(predictions,', 'labels,', 'weights_fn=common_layers.weights_nonzero):', 'outputs', '=', 'tf.squeeze(tf.to_int32(predictions))', 'labels', '=', 'tf.squeeze(labels)', 'weights', '=', 'weights_fn(labels)', 'labels', '=', 'tf.to_int32(labels)', 'return', '(tf.to_float(tf.equal(outputs,', 'labels)...
966,116
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
metrics.py
create_eager_metrics
create_eager_metrics
Create metrics accumulators and averager for Eager mode.
[ "Create", "metrics", "accumulators", "and", "averager", "for", "Eager", "mode." ]
def create_eager_metrics(metric_names, weights_fn=common_layers.weights_all): metric_fns = dict([(name, METRICS_FNS[name]) for name in metric_names]) tfe_metrics = dict() for name in metric_names: tfe_metrics[name] = tfe.metrics.Mean(name=name) def metric_accum(predictions, targets): fo...
['def', 'create_eager_metrics(metric_names,', 'weights_fn=common_layers.weights_all):', 'metric_fns', '=', 'dict([(name,', 'METRICS_FNS[name])', 'for', 'name', 'in', 'metric_names])', 'tfe_metrics', '=', 'dict()', 'for', 'name', 'in', 'metric_names:', 'tfe_metrics[name]', '=', 'tfe.metrics.Mean(name=name)', 'def', 'met...
966,129
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
metrics_copy.py
softmax_cross_entropy_one_hot
softmax_cross_entropy_one_hot
Calculate softmax cross entropy given one-hot labels and logits.
[ "Calculate", "softmax", "cross", "entropy", "given", "one-hot", "labels", "and", "logits." ]
def softmax_cross_entropy_one_hot(logits, labels, weights_fn=None): with tf.variable_scope('softmax_cross_entropy_one_hot', values=[logits, labels]): del weights_fn cross_entropy = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=logits) return (cross_entropy, tf.constant(1.0))
['def', 'softmax_cross_entropy_one_hot(logits,', 'labels,', 'weights_fn=None):', 'with', "tf.variable_scope('softmax_cross_entropy_one_hot',", 'values=[logits,', 'labels]):', 'del', 'weights_fn', 'cross_entropy', '=', 'tf.losses.softmax_cross_entropy(onehot_labels=labels,', 'logits=logits)', 'return', '(cross_entropy,'...
966,143
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
metrics_copy.py
sigmoid_accuracy_one_hot
sigmoid_accuracy_one_hot
Calculate accuracy for a set, given one-hot labels and logits.
[ "Calculate", "accuracy", "for", "a", "set,", "given", "one-hot", "labels", "and", "logits." ]
def sigmoid_accuracy_one_hot(logits, labels, weights_fn=None): with tf.variable_scope('sigmoid_accuracy_one_hot', values=[logits, labels]): del weights_fn predictions = tf.nn.sigmoid(logits) labels = tf.argmax(labels, -1) predictions = tf.argmax(predictions, -1) (_, accuracy)...
['def', 'sigmoid_accuracy_one_hot(logits,', 'labels,', 'weights_fn=None):', 'with', "tf.variable_scope('sigmoid_accuracy_one_hot',", 'values=[logits,', 'labels]):', 'del', 'weights_fn', 'predictions', '=', 'tf.nn.sigmoid(logits)', 'labels', '=', 'tf.argmax(labels,', '-1)', 'predictions', '=', 'tf.argmax(predictions,', ...
966,144
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
optimize.py
weight_noise
weight_noise
Apply weight noise to vars in var_list.
[ "Apply", "weight", "noise", "to", "vars", "in", "var_list." ]
def weight_noise(noise_rate, learning_rate, var_list): if not noise_rate: return [tf.no_op()] tf.logging.info('Applying weight noise scaled by learning rate, noise_rate: %0.5f', noise_rate) noise_ops = [] for v in var_list: with tf.device(v._ref().device): scale = noise_rate ...
['def', 'weight_noise(noise_rate,', 'learning_rate,', 'var_list):', 'if', 'not', 'noise_rate:', 'return', '[tf.no_op()]', "tf.logging.info('Applying", 'weight', 'noise', 'scaled', 'by', 'learning', 'rate,', 'noise_rate:', "%0.5f',", 'noise_rate)', 'noise_ops', '=', '[]', 'for', 'v', 'in', 'var_list:', 'with', 'tf.devic...
966,162
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
optimize.py
weight_decay
weight_decay
Apply weight decay to vars in var_list.
[ "Apply", "weight", "decay", "to", "vars", "in", "var_list." ]
def weight_decay(decay_rate, var_list, skip_biases=True): if not decay_rate: return 0.0 tf.logging.info('Applying weight decay, decay_rate: %0.5f', decay_rate) weight_decays = [] for v in var_list: is_bias = len(v.shape.as_list()) == 1 and v.name.endswith('bias:0') if not (skip_b...
['def', 'weight_decay(decay_rate,', 'var_list,', 'skip_biases=True):', 'if', 'not', 'decay_rate:', 'return', '0.0', "tf.logging.info('Applying", 'weight', 'decay,', 'decay_rate:', "%0.5f',", 'decay_rate)', 'weight_decays', '=', '[]', 'for', 'v', 'in', 'var_list:', 'is_bias', '=', 'len(v.shape.as_list())', '==', '1', 'a...
966,163
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
optimize.py
get_variable_initializer
get_variable_initializer
Get variable initializer from hparams.
[ "Get", "variable", "initializer", "from", "hparams." ]
def get_variable_initializer(hparams): if not hparams.initializer: return None if not tf.contrib.eager.in_eager_mode(): tf.logging.info('Using variable initializer: %s', hparams.initializer) if hparams.initializer == 'orthogonal': return tf.orthogonal_initializer(gain=hparams.initial...
['def', 'get_variable_initializer(hparams):', 'if', 'not', 'hparams.initializer:', 'return', 'None', 'if', 'not', 'tf.contrib.eager.in_eager_mode():', "tf.logging.info('Using", 'variable', 'initializer:', "%s',", 'hparams.initializer)', 'if', 'hparams.initializer', '==', "'orthogonal':", 'return', 'tf.orthogonal_initia...
966,165
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
pruning_utils.py
sparsify
sparsify
Prune the weights of a model and evaluate.
[ "Prune", "the", "weights", "of", "a", "model", "and", "evaluate." ]
def sparsify(sess, eval_model, pruning_strategy, pruning_params): weights = tf.trainable_variables() def should_prune(name): in_whitelist = not pruning_params.white_list or any((e in name for e in pruning_params.white_list)) in_blacklist = any((e in name for e in pruning_params.black_list)) ...
['def', 'sparsify(sess,', 'eval_model,', 'pruning_strategy,', 'pruning_params):', 'weights', '=', 'tf.trainable_variables()', 'def', 'should_prune(name):', 'in_whitelist', '=', 'not', 'pruning_params.white_list', 'or', 'any((e', 'in', 'name', 'for', 'e', 'in', 'pruning_params.white_list))', 'in_blacklist', '=', 'any((e...
966,166
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
quantization.py
bfloat16_activations_var_getter
bfloat16_activations_var_getter
A custom getter function for float32 parameters and bfloat16 activations.
[ "A", "custom", "getter", "function", "for", "float32", "parameters", "and", "bfloat16", "activations." ]
def bfloat16_activations_var_getter(getter, *args, **kwargs): requested_dtype = kwargs['dtype'] if requested_dtype == tf.bfloat16: kwargs['dtype'] = tf.float32 var = getter(*args, **kwargs) if var.dtype.base_dtype != requested_dtype: var = tf.cast(var, requested_dtype) return var
['def', 'bfloat16_activations_var_getter(getter,', '*args,', '**kwargs):', 'requested_dtype', '=', "kwargs['dtype']", 'if', 'requested_dtype', '==', 'tf.bfloat16:', "kwargs['dtype']", '=', 'tf.float32', 'var', '=', 'getter(*args,', '**kwargs)', 'if', 'var.dtype.base_dtype', '!=', 'requested_dtype:', 'var', '=', 'tf.cas...
966,167
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
quantization.py
ParameterEncoding.encode
encode
Encode float32 to bfloat16.
[ "Encode", "float32", "to", "bfloat16." ]
def encode(self, x, noise): raise NotImplementedError('encode not implemented')
['def', 'encode(self,', 'x,', 'noise):', 'raise', "NotImplementedError('encode", 'not', "implemented')"]
966,169
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
registry.py
default_name
default_name
Convert a class name to the registry's default name for the class.
[ "Convert", "a", "class", "name", "to", "the", "registry's", "default", "name", "for", "the", "class." ]
def default_name(obj_class): return _convert_camel_to_snake(obj_class.__name__)
['def', 'default_name(obj_class):', 'return', '_convert_camel_to_snake(obj_class.__name__)']
966,172
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
registry.py
attack_params
attack_params
Retrieve registered aparams by name.
[ "Retrieve", "registered", "aparams", "by", "name." ]
def attack_params(name): if name not in _ATTACK_PARAMS: error_msg = 'Attack HParams set %s never registered. Sets registered:\n%s' raise LookupError(error_msg % (name, display_list_by_prefix(list_attack_params(), starting_spaces=4))) ap = _ATTACK_PARAMS[name]() if ap is None: raise T...
['def', 'attack_params(name):', 'if', 'name', 'not', 'in', '_ATTACK_PARAMS:', 'error_msg', '=', "'Attack", 'HParams', 'set', '%s', 'never', 'registered.', 'Sets', "registered:\\n%s'", 'raise', 'LookupError(error_msg', '%', '(name,', 'display_list_by_prefix(list_attack_params(),', 'starting_spaces=4)))', 'ap', '=', '_AT...
966,183
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
registry.py
pruning_strategies
pruning_strategies
Retrieve registered pruning strategies by name.
[ "Retrieve", "registered", "pruning", "strategies", "by", "name." ]
def pruning_strategies(name): if name not in _PRUNING_STRATEGY: error_msg = 'Pruning strategy set %s never registered. Sets registered:\n%s' raise LookupError(error_msg % (name, display_list_by_prefix(list_pruning_strategies(), starting_spaces=4))) ps = _PRUNING_STRATEGY[name] if ps is None:...
['def', 'pruning_strategies(name):', 'if', 'name', 'not', 'in', '_PRUNING_STRATEGY:', 'error_msg', '=', "'Pruning", 'strategy', 'set', '%s', 'never', 'registered.', 'Sets', "registered:\\n%s'", 'raise', 'LookupError(error_msg', '%', '(name,', 'display_list_by_prefix(list_pruning_strategies(),', 'starting_spaces=4)))', ...
966,187
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
t2t_model.py
summarize_features
summarize_features
Generate summaries for features.
[ "Generate", "summaries", "for", "features." ]
def summarize_features(features, num_shards=1): if not common_layers.should_generate_summaries(): return with tf.name_scope('input_stats'): for (k, v) in sorted(six.iteritems(features)): if isinstance(v, tf.Tensor) and v.get_shape().ndims > 1: tf.summary.scalar('%s_ba...
['def', 'summarize_features(features,', 'num_shards=1):', 'if', 'not', 'common_layers.should_generate_summaries():', 'return', 'with', "tf.name_scope('input_stats'):", 'for', '(k,', 'v)', 'in', 'sorted(six.iteritems(features)):', 'if', 'isinstance(v,', 'tf.Tensor)', 'and', 'v.get_shape().ndims', '>', '1:', "tf.summary....
966,203
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
t2t_model.py
T2TModel.bottom
bottom
Transform features to feed into body.
[ "Transform", "features", "to", "feed", "into", "body." ]
def bottom(self, features): if not self._problem_hparams: log_warn('Without a Problem, T2TModel.bottom is a passthrough.') return features transformed_features = collections.OrderedDict() all_previous_modalities = [] for (key, input_modality) in sorted(six.iteritems(self._problem_hparams...
['def', 'bottom(self,', 'features):', 'if', 'not', 'self._problem_hparams:', "log_warn('Without", 'a', 'Problem,', 'T2TModel.bottom', 'is', 'a', "passthrough.')", 'return', 'features', 'transformed_features', '=', 'collections.OrderedDict()', 'all_previous_modalities', '=', '[]', 'for', '(key,', 'input_modality)', 'in'...
966,205
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
t2t_model.py
T2TModel.optimize
optimize
Return a training op minimizing loss.
[ "Return", "a", "training", "op", "minimizing", "loss." ]
def optimize(self, loss, num_async_replicas=1, use_tpu=False): 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.sqrt(float(num_async_replicas)) train_op = optimize.optimi...
['def', 'optimize(self,', 'loss,', 'num_async_replicas=1,', 'use_tpu=False):', '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.sqrt(float(num_as...
966,208
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
t2t_model.py
T2TModel.set_mode
set_mode
Set hparams with the given mode.
[ "Set", "hparams", "with", "the", "given", "mode." ]
def set_mode(self, mode): log_info("Setting T2TModel mode to '%s'", mode) hparams = copy.copy(self._original_hparams) hparams.add_hparam('mode', mode) if mode != tf.estimator.ModeKeys.TRAIN: for key in hparams.values(): if key.endswith('dropout') or key == 'label_smoothing': ...
['def', 'set_mode(self,', 'mode):', 'log_info("Setting', 'T2TModel', 'mode', 'to', '\'%s\'",', 'mode)', 'hparams', '=', 'copy.copy(self._original_hparams)', "hparams.add_hparam('mode',", 'mode)', 'if', 'mode', '!=', 'tf.estimator.ModeKeys.TRAIN:', 'for', 'key', 'in', 'hparams.values():', 'if', "key.endswith('dropout')"...
966,209
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
t2t_model.py
T2TModel.estimator_model_fn
estimator_model_fn
Model fn for Estimator.
[ "Model", "fn", "for", "Estimator." ]
def estimator_model_fn(cls, hparams, features, labels, mode, config=None, params=None, decode_hparams=None): if mode == tf.estimator.ModeKeys.TRAIN: _create_dummy_vars() hparams = copy.deepcopy(hparams) use_tpu = params and params.get('use_tpu', False) data_parallelism = None if not use_tpu ...
['def', 'estimator_model_fn(cls,', 'hparams,', 'features,', 'labels,', 'mode,', 'config=None,', 'params=None,', 'decode_hparams=None):', 'if', 'mode', '==', 'tf.estimator.ModeKeys.TRAIN:', '_create_dummy_vars()', 'hparams', '=', 'copy.deepcopy(hparams)', 'use_tpu', '=', 'params', 'and', "params.get('use_tpu',", 'False)...
966,214
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_lib.py
next_checkpoint
next_checkpoint
Yields successive checkpoints from model_dir.
[ "Yields", "successive", "checkpoints", "from", "model_dir." ]
def next_checkpoint(model_dir, timeout_mins=120): last_ckpt = None while True: last_ckpt = tf.contrib.training.wait_for_new_checkpoint(model_dir, last_ckpt, seconds_to_sleep=60, timeout=60 * timeout_mins) if last_ckpt is None: tf.logging.info('Eval timeout: no new checkpoints within ...
['def', 'next_checkpoint(model_dir,', 'timeout_mins=120):', 'last_ckpt', '=', 'None', 'while', 'True:', 'last_ckpt', '=', 'tf.contrib.training.wait_for_new_checkpoint(model_dir,', 'last_ckpt,', 'seconds_to_sleep=60,', 'timeout=60', '*', 'timeout_mins)', 'if', 'last_ckpt', 'is', 'None:', "tf.logging.info('Eval", 'timeou...
966,218
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_lib.py
create_run_config
create_run_config
Create RunConfig, TPUConfig, and Parallelism object.
[ "Create", "RunConfig,", "TPUConfig,", "and", "Parallelism", "object." ]
def create_run_config(master='', model_dir=None, iterations_per_loop=1000, num_shards=8, log_device_placement=False, save_checkpoints_steps=1000, save_checkpoints_secs=None, keep_checkpoint_max=20, keep_checkpoint_every_n_hours=10000, num_gpus=1, gpu_order='', shard_to_cpu=False, num_async_replicas=1, enable_graph_rewr...
['def', "create_run_config(master='',", 'model_dir=None,', 'iterations_per_loop=1000,', 'num_shards=8,', 'log_device_placement=False,', 'save_checkpoints_steps=1000,', 'save_checkpoints_secs=None,', 'keep_checkpoint_max=20,', 'keep_checkpoint_every_n_hours=10000,', 'num_gpus=1,', "gpu_order='',", 'shard_to_cpu=False,',...
966,221
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_lib.py
create_estimator
create_estimator
Create a T2T Estimator.
[ "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): model_fn = t2t_model.T2TModel.make_estimator_model_fn(model_name, hparams, decode_hparams=decode_hparams) del use_xla if use_tpu or use_tpu_estima...
['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):', 'model_fn', '=', 't2t_model.T2TModel.make_estimator_model_fn(model_name,', 'hparams,', 'decode_hparams=decode_hparams)', 'del', 'u...
966,222
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_lib.py
create_hooks
create_hooks
Create train and eval hooks for Experiment.
[ "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): train_hooks = [] eval_hooks = [] if use_tfdbg: hook = debug.LocalCLIDebugHook() train_hooks.app...
['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):', 'train_hooks', '=', '[]', 'eval_hooks', '=', '[]', 'if', 'use_tfdbg:', 'hook', '=', 'debug.LocalCL...
966,223
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_lib.py
restore_checkpoint
restore_checkpoint
Restore from a checkpoint.
[ "Restore", "from", "a", "checkpoint." ]
def restore_checkpoint(ckpt_dir, saver, sess, must_restore=False): ckpt = tf.train.get_checkpoint_state(ckpt_dir) if must_restore and (not ckpt): raise ValueError('No checkpoint found in %s' % ckpt_dir) if not ckpt: return 0 path = ckpt.model_checkpoint_path tf.logging.info('Restorin...
['def', 'restore_checkpoint(ckpt_dir,', 'saver,', 'sess,', 'must_restore=False):', 'ckpt', '=', 'tf.train.get_checkpoint_state(ckpt_dir)', 'if', 'must_restore', 'and', '(not', 'ckpt):', 'raise', "ValueError('No", 'checkpoint', 'found', 'in', "%s'", '%', 'ckpt_dir)', 'if', 'not', 'ckpt:', 'return', '0', 'path', '=', 'ck...
966,226
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_lib.py
T2TExperiment.test
test
Perform 1 step of train and 2 step of eval.
[ "Perform", "1", "step", "of", "train", "and", "2", "step", "of", "eval." ]
def test(self): if self._use_validation_monitor: return self.train_and_evaluate() self._estimator.train(self._train_spec.input_fn, hooks=self._train_spec.hooks, max_steps=1) self._estimator.evaluate(self._eval_spec.input_fn, steps=1, hooks=self._eval_spec.hooks)
['def', 'test(self):', 'if', 'self._use_validation_monitor:', 'return', 'self.train_and_evaluate()', 'self._estimator.train(self._train_spec.input_fn,', 'hooks=self._train_spec.hooks,', 'max_steps=1)', 'self._estimator.evaluate(self._eval_spec.input_fn,', 'steps=1,', 'hooks=self._eval_spec.hooks)']
966,229