code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_tpu_estimator(self,
run_config,
hparams,
train_steps,
train_batch_size,
eval_on_tpu,
embedding_config_spec=None,
eval_batch_size=None):
"""R... | Returns a Phoenix `Estimator` for train and evaluation.
Args:
run_config: `RunConfig` object to configure the runtime settings.
hparams: `HParams` instance defining custom hyperparameters.
train_steps: The total number of training steps.
train_batch_size: batch size for train.
eval_on... | get_tpu_estimator | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def get_keras_hyperparameters_space(phoenix_spec, train_steps):
"""Gets the Phoenix search space as keras Hyperparameters object."""
hp_space = keras_tuner.HyperParameters()
hp_space.merge(
architecture_utils.get_blocks_search_space(phoenix_spec.blocks_to_use))
hp_space.Float("learning_rate", 1e... | Gets the Phoenix search space as keras Hyperparameters object. | get_keras_hyperparameters_space | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def _create_phoenix_spec(self, problem_type):
"""Creates a new phoenix.PhoenixSpec for the given problem type."""
spec_path = os.path.join(FLAGS.test_srcdir,
_SPEC_PATH_TEMPLATE.format(problem_type))
spec = phoenix_spec_pb2.PhoenixSpec()
with tf.io.gfile.GFile(spec_path, "r"... | Creates a new phoenix.PhoenixSpec for the given problem type. | _create_phoenix_spec | python | google/model_search | model_search/phoenix_test.py | https://github.com/google/model_search/blob/master/model_search/phoenix_test.py | Apache-2.0 |
def _create_phoenix_instance(self,
problem_type,
input_shape=None,
head=None,
logits_dimension=None,
label_vocabulary=None,
loss_fn=No... | Creates a phoenix.Phoenix instance with mostly default parameters.
Args:
problem_type: The problem type (e.g. cnn, rnn, etc) for which to create a
PhoenixSpec.
input_shape: The shape of the input Tensor (including batch size).
head: The head to pass to the Phoenix instance.
logits_d... | _create_phoenix_instance | python | google/model_search | model_search/phoenix_test.py | https://github.com/google/model_search/blob/master/model_search/phoenix_test.py | Apache-2.0 |
def register(base,
init_args=None,
lookup_name=None,
enum_id=None,
add_name_to_args=False):
"""Produces a decorator to register a subclass of a base class, or a method.
This produces a decorator to register a subclass of a base class, or a method
which implemen... | Produces a decorator to register a subclass of a base class, or a method.
This produces a decorator to register a subclass of a base class, or a method
which implements the same signature as the given base method.
For example:
Example 1:
class Base(object):
...
@register(Base)
class Sub(Ba... | register | python | google/model_search | model_search/registry.py | https://github.com/google/model_search/blob/master/model_search/registry.py | Apache-2.0 |
def _register_decorator(cls_or_method):
"""A decorator to register a subclass of the base class or a method.
Args:
cls_or_method: A subclass or a method to be registered.
Raises:
ValueError: If any of the following rules are violated, the method will
raise a ValueError:
(1) c... | A decorator to register a subclass of the base class or a method.
Args:
cls_or_method: A subclass or a method to be registered.
Raises:
ValueError: If any of the following rules are violated, the method will
raise a ValueError:
(1) cls_or_method should either be a class or a meth... | _register_decorator | python | google/model_search | model_search/registry.py | https://github.com/google/model_search/blob/master/model_search/registry.py | Apache-2.0 |
def lookup(name, base, override_name=None):
"""Looks up a subclass of a base class from the registry.
Looks up a subclass of a base class with name provided from the
registry. Returns the registered subclass if found, None otherwise.
Args:
name: Name to look up from the registry.
base: The base class ... | Looks up a subclass of a base class from the registry.
Looks up a subclass of a base class with name provided from the
registry. Returns the registered subclass if found, None otherwise.
Args:
name: Name to look up from the registry.
base: The base class of the subclass to be found.
override_name: s... | lookup | python | google/model_search | model_search/registry.py | https://github.com/google/model_search/blob/master/model_search/registry.py | Apache-2.0 |
def modify_init_args(name, base, new_init_args):
"""Modifies init args for a subclass of a base class from the registry.
Args:
name: Name to look up from the registry.
base: The base class of the subclass to be found.
new_init_args: a kwargs dict with new args names and values.
Raises:
RuntimeEr... | Modifies init args for a subclass of a base class from the registry.
Args:
name: Name to look up from the registry.
base: The base class of the subclass to be found.
new_init_args: a kwargs dict with new args names and values.
Raises:
RuntimeError: in case name or base are not in registeries.
| modify_init_args | python | google/model_search | model_search/registry.py | https://github.com/google/model_search/blob/master/model_search/registry.py | Apache-2.0 |
def lookup_all(base):
"""Looks up a subclass of a base class from the registry.
Looks up a subclass of a base class with name provided from the
registry. Returns a list of registered subclass if found, None otherwise.
Args:
base: The base class of the subclass to be found.
Returns:
A list of subcla... | Looks up a subclass of a base class from the registry.
Looks up a subclass of a base class with name provided from the
registry. Returns a list of registered subclass if found, None otherwise.
Args:
base: The base class of the subclass to be found.
Returns:
A list of subclass of the name if found, No... | lookup_all | python | google/model_search | model_search/registry.py | https://github.com/google/model_search/blob/master/model_search/registry.py | Apache-2.0 |
def try_models(self, number_models, train_steps, eval_steps, root_dir,
batch_size, experiment_name, experiment_owner):
"""Simple function to invoke automl on one machine.
Args:
number_models: The number of neural networks to try.
train_steps: The number of steps to train every cand... | Simple function to invoke automl on one machine.
Args:
number_models: The number of neural networks to try.
train_steps: The number of steps to train every candidate architecture.
eval_steps: The number of steps to evaluated every candidate architecture.
root_dir: The root directory to writ... | try_models | python | google/model_search | model_search/single_trainer.py | https://github.com/google/model_search/blob/master/model_search/single_trainer.py | Apache-2.0 |
def _get_optimizer_fn(optimizer,
learning_rate,
use_tpu,
exponential_decay_steps=-1,
exponential_decay_rate=-1,
lr_warmup_steps=0):
"""Returns a function that gives the optimizer."""
def optimizer_fn():
... | Returns a function that gives the optimizer. | _get_optimizer_fn | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def _compute_tolerance(workers):
"""Computes how many workers can be ignored for one gradient update.
These numbers were chosen based on just a few expriments. They are rather
arbitrary, feel free to change them.
Args:
workers: Number of workers used during computations.
Returns:
int: how many wor... | Computes how many workers can be ignored for one gradient update.
These numbers were chosen based on just a few expriments. They are rather
arbitrary, feel free to change them.
Args:
workers: Number of workers used during computations.
Returns:
int: how many workers can be preemptied during one step... | _compute_tolerance | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def _train_op_fn(loss,
optimizer_fn,
l2_regularization=-1,
gradient_max_norm=-1,
use_synchronous_optimizer=False):
"""Returns the op to optimize the loss.
Supports l2 regularization, learning rate decay and gradient clipping.
Args:
loss: Th... | Returns the op to optimize the loss.
Supports l2 regularization, learning rate decay and gradient clipping.
Args:
loss: The training loss before regularization.
optimizer_fn: the optimization function.
l2_regularization: a float that will multiply the l2 weight norms in the
loss function.
gr... | _train_op_fn | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def _create_task_spec(self,
labels,
weights,
train_logits_specs,
eval_logits_spec,
train_op_fn,
name,
mode,
loss_fn,
... | Creates the task spec for a task. | _create_task_spec | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def _get_loss_fn(self,
original_loss_fn,
features,
mode,
my_id,
teacher_logits_spec=None):
"""Gets the applicable loss_fn to use.
If head is not None, wraps the head's loss function to match the interface
Phoenix... | Gets the applicable loss_fn to use.
If head is not None, wraps the head's loss function to match the interface
Phoenix expects (see loss_fns.py), unless distillation is being used.
Args:
original_loss_fn: The original loss_fn from the user.
features: The features pass to model_fn.
mode: ... | _get_loss_fn | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def head_loss_fn(labels, logits, weights=1.0):
"""Create a loss fn from the Head object."""
del weights # Head already has weights built in.
training_loss = None
# There is two types of head, and their api is different.
if getattr(self._head, "loss", None) is not None:
training_l... | Create a loss fn from the Head object. | head_loss_fn | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def get_train_and_eval_logits(self, towers, trial_mode):
"""Helper function to get the various logits for a task."""
priors_logits_specs = []
search_logits_specs = []
if base_tower_generator.SEARCH_GENERATOR in towers.keys():
search_logits_specs = [
t.logits_spec for t in towers[base_tow... | Helper function to get the various logits for a task. | get_train_and_eval_logits | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def create_model_spec(self,
features,
params,
learning_rate_spec,
use_tpu,
trial_mode,
towers,
labels,
mode,
... | Creates model spec for all tasks. | create_model_spec | python | google/model_search | model_search/task_manager.py | https://github.com/google/model_search/blob/master/model_search/task_manager.py | Apache-2.0 |
def last_activations_in_sequence(activations, sequence_lengths=None):
"""Selects the nth set of activations for each n in `sequence_length`.
Returns a `Tensor` of shape `[batch_size, k]`. If `sequence_length` is not
`None`, then `output[i, :] = activations[i, sequence_length[i] - 1, :]`. If
`sequence_length` i... | Selects the nth set of activations for each n in `sequence_length`.
Returns a `Tensor` of shape `[batch_size, k]`. If `sequence_length` is not
`None`, then `output[i, :] = activations[i, sequence_length[i] - 1, :]`. If
`sequence_length` is `None`, then `output[i, :] = activations[i, -1, :]`.
Args:
activat... | last_activations_in_sequence | python | google/model_search | model_search/utils.py | https://github.com/google/model_search/blob/master/model_search/utils.py | Apache-2.0 |
def get_trial_id(directory, phoenix_spec):
"""Returns the trial id - best effort, None if unable.
Args:
directory: model directory (string).
phoenix_spec: PhoenixSpec proto.
Returns:
an integer holding the trial id. Works for regular trial runs where the
trial id is the directory n... | Returns the trial id - best effort, None if unable.
Args:
directory: model directory (string).
phoenix_spec: PhoenixSpec proto.
Returns:
an integer holding the trial id. Works for regular trial runs where the
trial id is the directory name, and for TFX pipelines, where the trial
... | get_trial_id | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def get_architecture(directory, tower_name="search_generator_0"):
"""Given a trial directory and a tower name, returns its architecture.
Args:
directory: string - a model directory (that includes checkpoints).
tower_name: string - the tower name we are trying to retrieve the
architecutre for.
Retu... | Given a trial directory and a tower name, returns its architecture.
Args:
directory: string - a model directory (that includes checkpoints).
tower_name: string - the tower name we are trying to retrieve the
architecutre for.
Returns:
np.array of ints holding the architecture of the Phoenix tower... | get_architecture | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def set_architecture(architecture, tower_name="search_generator_0"):
"""Saves the tower architecture to the checkpoint as a tensor.
Args:
architecture: np.array of ints - holding the architecture.
tower_name: string - the tower name we are trying to set the architecutre
for.
"""
tf.compat.v1.get_... | Saves the tower architecture to the checkpoint as a tensor.
Args:
architecture: np.array of ints - holding the architecture.
tower_name: string - the tower name we are trying to set the architecutre
for.
| set_architecture | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def get_architecture_size(tower_name="search_generator_0"):
"""Returns the number of blocks of the architecture or None if ensembling."""
prefix = "architectures/{}".format(tower_name)
architecture = [
var for var in tf.compat.v1.global_variables() if prefix in var.name
]
assert len(architecture) <= 1
... | Returns the number of blocks of the architecture or None if ensembling. | get_architecture_size | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def get_number_of_towers(directory, generator_name):
"""Given a trial directory and a generator name, returns the number of towers.
Args:
directory: string - a model directory (that includes checkpoints).
generator_name: string - the generator name that built the towers.
Returns:
np.array of ints - ... | Given a trial directory and a generator name, returns the number of towers.
Args:
directory: string - a model directory (that includes checkpoints).
generator_name: string - the generator name that built the towers.
Returns:
np.array of ints - holding the number of towers (one integer) the generator
... | get_number_of_towers | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def set_number_of_towers(generator_name, number_of_towers):
"""Saves the number of towers a generator has in the checkpoint as a tensor.
Args:
generator_name: string - the name of the generator.
number_of_towers: int - the number of towers the generator created.
"""
tf.compat.v1.get_variable(
nam... | Saves the number of towers a generator has in the checkpoint as a tensor.
Args:
generator_name: string - the name of the generator.
number_of_towers: int - the number of towers the generator created.
| set_number_of_towers | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def get_parameter(directory, tower_name, parameter_name):
"""Get a param given a trial directory, a tower, and the parameter name.
Args:
directory: string - a model directory (that includes checkpoints).
tower_name: string - the tower name.
parameter_name: string - the parameter name.
Returns:
n... | Get a param given a trial directory, a tower, and the parameter name.
Args:
directory: string - a model directory (that includes checkpoints).
tower_name: string - the tower name.
parameter_name: string - the parameter name.
Returns:
np.array - holding the parameter.
| get_parameter | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def set_parameter(tower_name, parameter_name, value, dtype=tf.int32):
"""Saves a tower's parameter in the checkpoint as a tensor.
Args:
tower_name: string - the name of the tower.
parameter_name: string - the name of the parameter.
value: the value you wish to store.
dtype: the type of the value. E... | Saves a tower's parameter in the checkpoint as a tensor.
Args:
tower_name: string - the name of the tower.
parameter_name: string - the name of the parameter.
value: the value you wish to store.
dtype: the type of the value. E.g., tf.int32.
| set_parameter | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def fix_architecture_order(architecture, problem_type):
"""Fixes the architecture order of cnns.
This function fixes the architecture for convolutional neural networks.
Namely, if a dense block is before a convolutional block, then it switches
the order. For the dnn and rnn case, the function doesn't do anythi... | Fixes the architecture order of cnns.
This function fixes the architecture for convolutional neural networks.
Namely, if a dense block is before a convolutional block, then it switches
the order. For the dnn and rnn case, the function doesn't do anything for
the architecture as all architectures are valid.
... | fix_architecture_order | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def increase_structure_depth(previous_architecture, added_block, problem_type):
"""Returns new structure given the old one and the added block.
Increases the depth of the neural network by adding `added_block`.
For the case of cnns, if the block is convolutional, it will add it before
the flattening operation.... | Returns new structure given the old one and the added block.
Increases the depth of the neural network by adding `added_block`.
For the case of cnns, if the block is convolutional, it will add it before
the flattening operation. Otherwise, if it is a dense block, then it will
be added at the end.
For the dnn... | increase_structure_depth | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def init_variables(checkpoint, original_scope, new_scope):
"""Best effort: Initializes variables in a scope from a checkpoint.
This function aims to warm start variables in a given scope from a
checkpoint. The function will not fail if a variable was not found in the
checkpoint. The function will fail if we ar... | Best effort: Initializes variables in a scope from a checkpoint.
This function aims to warm start variables in a given scope from a
checkpoint. The function will not fail if a variable was not found in the
checkpoint. The function will fail if we are trying to warmstart a sharded
variable from the checkpoint.
... | init_variables | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def strip_scope(scope, transfer_learning_type, str_signature):
"""Strips signature from the scope if uniform average transfer learning.
If we are warm starting the tower with the average values of the previous
trials, do not append the signature to the scope as this will cause a mismatch
when searching via mut... | Strips signature from the scope if uniform average transfer learning.
If we are warm starting the tower with the average values of the previous
trials, do not append the signature to the scope as this will cause a mismatch
when searching via mutation.
Args:
scope: The scope to potentially strip.
trans... | strip_scope | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def construct_tower(phoenix_spec,
input_tensor,
tower_name,
architecture,
is_training,
lengths,
logits_dimension,
is_frozen,
hparams,
model_... | Creates a tower giving an architecture.
Args:
phoenix_spec: The trial's `phoenix_spec_pb2.PhoenixSpec` proto.
input_tensor: An input `tf.Tensor` to build the network on top of. Can be
also a list of tensors if the first build block expects a list. If you
are using our own default blocks, then usi... | construct_tower | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def import_tower(phoenix_spec,
features,
input_layer_fn,
shared_input_tensor,
original_tower_name,
new_tower_name,
model_directory,
new_model_directory,
is_training,
l... | Imports a tower from the given model directory and the tower's name.
Args:
phoenix_spec: The trial's `phoenix_spec_pb2.PhoenixSpec` proto.
features: feature dict in case the tower needs to create the input tensor
input_layer_fn: A function that converts feature Tensors to input layer.
See learning.... | import_tower | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def get_tower_variables(tower_name):
"""Returns all the variables belonging to the tower with the given name."""
prefix = "Phoenix/{}".format(tower_name)
return [
var for var in tf.compat.v1.trainable_variables() if prefix in var.name
] | Returns all the variables belonging to the tower with the given name. | get_tower_variables | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def create_tower_spec(phoenix_spec,
inputs,
architecture,
dimension,
is_frozen,
lengths=None,
allow_auxiliary_head=False):
"""Creates the logits for the tower.
Args:
phoenix_spec:... | Creates the logits for the tower.
Args:
phoenix_spec: The trial's `phoenix_spec_pb2.PhoenixSpec` proto.
inputs: The list of `tf.Tensors` of the tower.
architecture: The list of `block_builder.BlockType` of the tower
architecture.
dimension: int - the output tensor last axis dimension.
is_fr... | create_tower_spec | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def _build_nas_aux_head(inputs, dimension, data_format):
"""Builds the auxiliary head described in the NAS paper."""
shape = inputs.shape
if shape.rank < 4:
return None
shape = shape.as_list()
shape = shape[1:3] if data_format == "NHWC" else shape[2:4]
if np.any(np.array(shape) < np.array([5, 5])):
... | Builds the auxiliary head described in the NAS paper. | _build_nas_aux_head | python | google/model_search | model_search/architecture/architecture_utils.py | https://github.com/google/model_search/blob/master/model_search/architecture/architecture_utils.py | Apache-2.0 |
def _compute_paddings(height_pad_amt, width_pad_amt, patch_axes):
"""Convert the total pad amounts to the format needed by tf.pad()."""
top_pad = height_pad_amt // 2
bottom_pad = height_pad_amt - top_pad
left_pad = width_pad_amt // 2
right_pad = width_pad_amt - left_pad
paddings = [[0, 0] for _ in range(4... | Convert the total pad amounts to the format needed by tf.pad(). | _compute_paddings | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def _pad_to_match(tensor_list, patch_axes):
"""Pads outputs of CNN examples until the patch sizes are equal."""
tensor_heights = [tensor.shape[patch_axes[0]] for tensor in tensor_list]
new_height = max(tensor_heights)
height_pad_amts = [
new_height - tensor_height for tensor_height in tensor_heights
]
... | Pads outputs of CNN examples until the patch sizes are equal. | _pad_to_match | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def __call__(self, inputs, **kwargs):
"""Combines inputs to produce the Tensor(s) used by the next Block.
Args:
inputs: A list of Tensors selected by the InputSelector. Returns a list
of Tensors to be used as input layers.
**kwargs: Allows data_format to be propagated using arg_scope.
... | Combines inputs to produce the Tensor(s) used by the next Block.
Args:
inputs: A list of Tensors selected by the InputSelector. Returns a list
of Tensors to be used as input layers.
**kwargs: Allows data_format to be propagated using arg_scope.
Returns:
A list of Tensors after being... | __call__ | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def __new__(cls, block_type, input_indices=None, combiner_type=None):
"""Constructs an Node.
Args:
block_type: int for the Block type.
input_indices: List of ints that determines which previous layers to pass
to the next Combiner. For example, [-1] means to pass the only the
output ... | Constructs an Node.
Args:
block_type: int for the Block type.
input_indices: List of ints that determines which previous layers to pass
to the next Combiner. For example, [-1] means to pass the only the
output of the previous block, [-2, -1] means to pass the outputs of the
prev... | __new__ | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def __new__(cls, node_list, input_keys=None, tower_name="search_generator_0"):
"""Constructs an Architecture.
Args:
node_list: List of Nodes. The first Node is closest to the inputs, the
last Node is closest to the outputs.
input_keys: List of string keys, which fixes the order of the input... | Constructs an Architecture.
Args:
node_list: List of Nodes. The first Node is closest to the inputs, the
last Node is closest to the outputs.
input_keys: List of string keys, which fixes the order of the input
Tensors from the input dict passed into construct_tower call. If None,
... | __new__ | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def create_logits_spec(self,
phoenix_spec,
pre_logits,
dimension,
is_frozen,
lengths=None):
"""Creates the logits for the tower.
Args:
phoenix_spec: The trial's `phoenix_spec_pb2.P... | Creates the logits for the tower.
Args:
phoenix_spec: The trial's `phoenix_spec_pb2.PhoenixSpec` proto.
pre_logits: `tf.Tensor` of the layer before the logits layer.
dimension: int - the output tensor last axis dimension.
is_frozen: Whether the tower should be frozen.
lengths: A tenso... | create_logits_spec | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def construct_tower(self,
phoenix_spec,
input_tensor,
is_training,
lengths,
logits_dimension,
is_frozen,
dropout_rate=None):
"""Creates a tower.
Forked from ... | Creates a tower.
Forked from architecture_utils.construct_tower.
Args:
phoenix_spec: The trial's `phoenix_spec_pb2.PhoenixSpec` proto.
input_tensor: An input `tf.Tensor` or a Dict[str, tf.Tensor] to build the
network on top of.
is_training: a boolean indicating if we are in training.... | construct_tower | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def save_to_graph(self):
"""Creates the variables in the tf.Graph.
Helps in saving the architecture to from Checkpoint. This does not save the
computation graph or trainable variables themselves, only the high-level
structure.
"""
input_indices_padded_name = "architectures/{}/{}".format(
... | Creates the variables in the tf.Graph.
Helps in saving the architecture to from Checkpoint. This does not save the
computation graph or trainable variables themselves, only the high-level
structure.
| save_to_graph | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def old_to_new_architecture(old_architecture):
"""Convert architectures defined by block_types only.
These architectures are more restricted -- they always have one input layer
and one logits layer, and all blocks are only connected to the previous one or
two blocks.
Args:
old_architecture: List of bloc... | Convert architectures defined by block_types only.
These architectures are more restricted -- they always have one input layer
and one logits layer, and all blocks are only connected to the previous one or
two blocks.
Args:
old_architecture: List of block_type ints.
Returns:
Architecture.
| old_to_new_architecture | python | google/model_search | model_search/architecture/graph_architecture.py | https://github.com/google/model_search/blob/master/model_search/architecture/graph_architecture.py | Apache-2.0 |
def load(phoenix_spec,
original_tower_name,
new_tower_name,
model_directory,
new_model_directory,
is_training,
logits_dimension,
force_freeze=False,
allow_auxiliary_head=False,
skip_initialization=False):
"""Imports a... | Imports a tower from the given model directory and the tower's name.
Args:
phoenix_spec: The trial's `phoenix_spec_pb2.PhoenixSpec` proto.
original_tower_name: a unique name for the tower (string) to import.
new_tower_name: the name to give the new tower.
model_directory: string, holds the ... | load | python | google/model_search | model_search/architecture/tower.py | https://github.com/google/model_search/blob/master/model_search/architecture/tower.py | Apache-2.0 |
def get_serving_input_fn(self, hparams):
"""Returns an `input_fn` for serving in an exported SavedModel.
Args:
hparams: tf.HParams object.
Returns:
Returns an `input_fn` that takes no arguments and returns a
`ServingInputReceiver`.
"""
features_ind = [
idx for idx in se... | Returns an `input_fn` for serving in an exported SavedModel.
Args:
hparams: tf.HParams object.
Returns:
Returns an `input_fn` that takes no arguments and returns a
`ServingInputReceiver`.
| get_serving_input_fn | python | google/model_search | model_search/data/csv_data.py | https://github.com/google/model_search/blob/master/model_search/data/csv_data.py | Apache-2.0 |
def get_keras_input(self, batch_size):
"""Returns keras input as explained in data.py module."""
del batch_size
dataset = pd.read_csv(self._filename)
labels = dataset.pop(dataset.columns.values[self._label_index])
labels = np.array(labels)
features = np.array(dataset)
validation_features = ... | Returns keras input as explained in data.py module. | get_keras_input | python | google/model_search | model_search/data/csv_data.py | https://github.com/google/model_search/blob/master/model_search/data/csv_data.py | Apache-2.0 |
def get_input_fn(self, hparams, mode, batch_size):
"""Returns an `input_fn` for train and evaluation.
Args:
hparams: tf.HParams for the experiment.
mode: Defines whether this is training or evaluation. See
`estimator.ModeKeys`.
batch_size: the batch size for training and eval.
Re... | Returns an `input_fn` for train and evaluation.
Args:
hparams: tf.HParams for the experiment.
mode: Defines whether this is training or evaluation. See
`estimator.ModeKeys`.
batch_size: the batch size for training and eval.
Returns:
Returns an `input_fn` for train or evaluation... | get_input_fn | python | google/model_search | model_search/data/data.py | https://github.com/google/model_search/blob/master/model_search/data/data.py | Apache-2.0 |
def get_serving_input_fn(self, hparams):
"""Returns an `input_fn` for serving in an exported SavedModel.
Args:
hparams: tf.HParams for the experiment.
Returns:
Returns an `input_fn` that takes no arguments and returns a
`ServingInputReceiver`.
""" | Returns an `input_fn` for serving in an exported SavedModel.
Args:
hparams: tf.HParams for the experiment.
Returns:
Returns an `input_fn` that takes no arguments and returns a
`ServingInputReceiver`.
| get_serving_input_fn | python | google/model_search | model_search/data/data.py | https://github.com/google/model_search/blob/master/model_search/data/data.py | Apache-2.0 |
def get_input_layer_fn(self, problem_type):
"""Provides the function for converting feature Tensors to an input layer.
Most users do not need to modify this function. In the typical use case,
the user would only need to implement `get_feature_columns`, and the default
implementation of this method woul... | Provides the function for converting feature Tensors to an input layer.
Most users do not need to modify this function. In the typical use case,
the user would only need to implement `get_feature_columns`, and the default
implementation of this method would take care of converting the feature
Tensors i... | get_input_layer_fn | python | google/model_search | model_search/data/data.py | https://github.com/google/model_search/blob/master/model_search/data/data.py | Apache-2.0 |
def _wait_for_chief(self, model_dir):
"""Waits on a directory till a checkpoint appears in it.
Args:
model_dir: string - the directory to wait on.
"""
my_id = architecture_utils.DirectoryHandler.get_trial_id(
model_dir, self._phoenix_spec)
while not tf.train.latest_checkpoint(model_di... | Waits on a directory till a checkpoint appears in it.
Args:
model_dir: string - the directory to wait on.
| _wait_for_chief | python | google/model_search | model_search/generators/base_tower_generator.py | https://github.com/google/model_search/blob/master/model_search/generators/base_tower_generator.py | Apache-2.0 |
def _build_from_existing_checkpoint(self, model_dir, trial_mode,
logits_dimension, is_training):
"""Builds the neural network from an existing checkpoint.
This function builds or replicates the model network given a model_dir with
a checkpoint.
Args:
model_d... | Builds the neural network from an existing checkpoint.
This function builds or replicates the model network given a model_dir with
a checkpoint.
Args:
model_dir: a string holding the directory of the model. Must have a
checkpoint in it.
trial_mode: the TrialMode for the current Phoenix... | _build_from_existing_checkpoint | python | google/model_search | model_search/generators/base_tower_generator.py | https://github.com/google/model_search/blob/master/model_search/generators/base_tower_generator.py | Apache-2.0 |
def generate(self, input_layer_fn, trial_mode, logits_dimension, hparams,
run_config, is_training, trials) -> List[tower.Tower]:
"""Generates the next architecture to try.
Args:
input_layer_fn: A function that converts feature Tensors to input layer.
See learning.autolx.model_searc... | Generates the next architecture to try.
Args:
input_layer_fn: A function that converts feature Tensors to input layer.
See learning.autolx.model_search.data.Provider.get_input_layer_fn
for details.
trial_mode: the TrialMode for the current Phoenix trial.
logits_dimension: An int h... | generate | python | google/model_search | model_search/generators/base_tower_generator.py | https://github.com/google/model_search/blob/master/model_search/generators/base_tower_generator.py | Apache-2.0 |
def first_time_chief_generate(self, input_layer_fn, trial_mode,
logits_dimension, hparams, run_config,
is_training, trials):
"""Creates the prior for the ensemble."""
del input_layer_fn
my_id = architecture_utils.DirectoryHandler.get_trial_id(
... | Creates the prior for the ensemble. | first_time_chief_generate | python | google/model_search | model_search/generators/prior_generator.py | https://github.com/google/model_search/blob/master/model_search/generators/prior_generator.py | Apache-2.0 |
def _suggest_and_create_architecture(create_new_architecture_fn,
relevant_trials, hparams, my_id,
run_config, search_algorithm, phoenix_spec,
input_layer_fn, is_training,
l... | A function to suggest and create an archiecture.
Args:
create_new_architecture_fn: A function to create the architecture with the
following signature Input architecture, A list of block encoding the
architecture. prev_trial, A trial if mutating a previous trial, otherwise
None. input_tensor, A... | _suggest_and_create_architecture | python | google/model_search | model_search/generators/search_candidate_generator.py | https://github.com/google/model_search/blob/master/model_search/generators/search_candidate_generator.py | Apache-2.0 |
def get_trial_mode(ensemble_spec, distillation_spec, trial_id):
"""Determines whether to bundle logits with Ensembler or Distiller.
If distillation and ensembling are specified at the same time, checks pool
sizes to see which phase this trial falls in. If the pool sizes are the same,
then defaults to ENSEMBLE_... | Determines whether to bundle logits with Ensembler or Distiller.
If distillation and ensembling are specified at the same time, checks pool
sizes to see which phase this trial falls in. If the pool sizes are the same,
then defaults to ENSEMBLE_SEARCH.
Args:
ensemble_spec: The spec defined in the Phoenix s... | get_trial_mode | python | google/model_search | model_search/generators/trial_utils.py | https://github.com/google/model_search/blob/master/model_search/generators/trial_utils.py | Apache-2.0 |
def get_intermixed_trials(trials, n, n_user_suggestions):
"""Filters the exploration trials for intermixed ensemble search."""
return [
trial for trial in trials
if trial.id % n != 0 or trial.id <= n_user_suggestions
] | Filters the exploration trials for intermixed ensemble search. | get_intermixed_trials | python | google/model_search | model_search/generators/trial_utils.py | https://github.com/google/model_search/blob/master/model_search/generators/trial_utils.py | Apache-2.0 |
def create_test_trials_intermixed(root_dir):
"""Creates fake trials used for testing."""
trials = [{
'model_dir': os.path.join(root_dir, str(2)),
'id': 2,
'status': 'COMPLETED',
'trial_infeasible': False,
'final_measurement': {
'objective_value': 0.94
},
}, {
'm... | Creates fake trials used for testing. | create_test_trials_intermixed | python | google/model_search | model_search/generators/trial_utils.py | https://github.com/google/model_search/blob/master/model_search/generators/trial_utils.py | Apache-2.0 |
def import_towers_one_trial(phoenix_spec, is_training, logits_dimension,
prev_model_dir, force_freeze, allow_auxiliary_head,
caller_generator, my_model_dir):
"""Imports a previous trial to current model."""
towers = []
imported_towers = 0
for generator in ... | Imports a previous trial to current model. | import_towers_one_trial | python | google/model_search | model_search/generators/trial_utils.py | https://github.com/google/model_search/blob/master/model_search/generators/trial_utils.py | Apache-2.0 |
def import_towers_multiple_trials(phoenix_spec, is_training, logits_dimension,
previous_model_dirs, force_freeze,
allow_auxiliary_head, caller_generator,
my_model_dir):
"""Imports search generators' model from many t... | Imports search generators' model from many trials. | import_towers_multiple_trials | python | google/model_search | model_search/generators/trial_utils.py | https://github.com/google/model_search/blob/master/model_search/generators/trial_utils.py | Apache-2.0 |
def write_replay_spec(model_dir, filename, original_spec, search_architecture,
hparams):
"""Writes a replay spec to retrain the same model."""
# Ensure the same search space as the original run
replay_spec = copy.deepcopy(original_spec)
# Remove user suggestions
replay_spec.ClearField('u... | Writes a replay spec to retrain the same model. | write_replay_spec | python | google/model_search | model_search/generators/trial_utils.py | https://github.com/google/model_search/blob/master/model_search/generators/trial_utils.py | Apache-2.0 |
def merge(self, hps, name_prefix="", overwrite=True):
"""Merges hyperparameters into this object.
Arguments:
hps: A `HyperParameters` object or list of `HyperParameter` objects.
name_prefix: A string to add to all hparams names in hps.
overwrite: bool. Whether existing `HyperParameter`s shoul... | Merges hyperparameters into this object.
Arguments:
hps: A `HyperParameters` object or list of `HyperParameter` objects.
name_prefix: A string to add to all hparams names in hps.
overwrite: bool. Whether existing `HyperParameter`s should be overridden
by those in `hps` with the same name ... | merge | python | google/model_search | model_search/hparams/hyperparameters.py | https://github.com/google/model_search/blob/master/model_search/hparams/hyperparameters.py | Apache-2.0 |
def get_distillation_loss_fn(teacher_logits, distillation_spec, my_id,
original_loss_fn):
"""Force the loss_fn to compare the student logits to the teacher logits."""
# The logits input below is the student logits
def _mse_teacher_loss_fn(labels, logits, weights=1.0):
"""A mean s... | Force the loss_fn to compare the student logits to the teacher logits. | get_distillation_loss_fn | python | google/model_search | model_search/meta/distillation.py | https://github.com/google/model_search/blob/master/model_search/meta/distillation.py | Apache-2.0 |
def _mse_teacher_loss_fn(labels, logits, weights=1.0):
"""A mean square error with the teacher's logits/predictions."""
del labels # Unused.
return tf.compat.v1.losses.mean_squared_error(
labels=teacher_logits, predictions=logits, weights=weights) | A mean square error with the teacher's logits/predictions. | _mse_teacher_loss_fn | python | google/model_search | model_search/meta/distillation.py | https://github.com/google/model_search/blob/master/model_search/meta/distillation.py | Apache-2.0 |
def _cross_entropy_loss_fn(labels, logits, weights=1.0):
"""A cross entropy with the teacher's predictions."""
del labels # Unused.
return tf.compat.v1.losses.softmax_cross_entropy(
onehot_labels=teacher_logits, logits=logits, weights=weights) | A cross entropy with the teacher's predictions. | _cross_entropy_loss_fn | python | google/model_search | model_search/meta/distillation.py | https://github.com/google/model_search/blob/master/model_search/meta/distillation.py | Apache-2.0 |
def _adaptively_balance_losses_loss_fn(loss1_fn,
loss2_fn,
labels,
logits,
weights=1.0):
"""Increasingly grow the distillation loss over time."""
or... | Increasingly grow the distillation loss over time. | _adaptively_balance_losses_loss_fn | python | google/model_search | model_search/meta/distillation.py | https://github.com/google/model_search/blob/master/model_search/meta/distillation.py | Apache-2.0 |
def bundle_logits(self, priors_logits_specs, search_logits_specs):
"""Bundles the priors and the search candidate."""
assert search_logits_specs, "Cannot distill with no student model."
assert len(search_logits_specs) == 1, "Search has more than one tower."
if not priors_logits_specs:
return Dis... | Bundles the priors and the search candidate. | bundle_logits | python | google/model_search | model_search/meta/distillation.py | https://github.com/google/model_search/blob/master/model_search/meta/distillation.py | Apache-2.0 |
def __init__(self, vars_to_warm_start, current_trial_id, completed_trials,
discount_factor, max_completed_trials, model_dir):
"""Initializes a new BaseTransferLearningHoook instance.
Args:
vars_to_warm_start: The variables to warm start from previous trials.
current_trial_id: The id ... | Initializes a new BaseTransferLearningHoook instance.
Args:
vars_to_warm_start: The variables to warm start from previous trials.
current_trial_id: The id of the current trial.
completed_trials: The list of successfully completed trials. Will be used
to warm start the variables of the cur... | __init__ | python | google/model_search | model_search/meta/transfer_learning.py | https://github.com/google/model_search/blob/master/model_search/meta/transfer_learning.py | Apache-2.0 |
def _sort_previous_trial_variables(self, trial_to_var):
"""Sorts trial_to_var in an order implemented by the subclass.
Args:
trial_to_var: A list of (Trial, tf.Variable) tuples corresponding to
previous trial variables which match variables in the current trial.
Returns:
The trial_to_v... | Sorts trial_to_var in an order implemented by the subclass.
Args:
trial_to_var: A list of (Trial, tf.Variable) tuples corresponding to
previous trial variables which match variables in the current trial.
Returns:
The trial_to_var list in sorted order.
| _sort_previous_trial_variables | python | google/model_search | model_search/meta/transfer_learning.py | https://github.com/google/model_search/blob/master/model_search/meta/transfer_learning.py | Apache-2.0 |
def _combine_previous_trial_variables(self, trial_to_var):
"""Combines the variables from previous trials.
Args:
trial_to_var: A list of (Trial, tf.Variable) tuples corresponding to
previous trial variables which match variables in the current trial.
Returns:
The tf.Variable with the c... | Combines the variables from previous trials.
Args:
trial_to_var: A list of (Trial, tf.Variable) tuples corresponding to
previous trial variables which match variables in the current trial.
Returns:
The tf.Variable with the combined value of all variables.
| _combine_previous_trial_variables | python | google/model_search | model_search/meta/transfer_learning.py | https://github.com/google/model_search/blob/master/model_search/meta/transfer_learning.py | Apache-2.0 |
def begin(self):
"""Creates the ops needed to warm start the model's variables."""
# Do not warm start the model if a checkopint already exists. If the model
# has already been training, we do not want to overwrite its variables.
if tf.train.latest_checkpoint(self._model_dir):
return
if not se... | Creates the ops needed to warm start the model's variables. | begin | python | google/model_search | model_search/meta/transfer_learning.py | https://github.com/google/model_search/blob/master/model_search/meta/transfer_learning.py | Apache-2.0 |
def _create_previous_trials(self, root_dir, shapes, dtypes, values):
"""Creates checkpoints for previous trials and returns num created."""
assert len(shapes) == len(dtypes) == len(values)
for i, (shape, dtype, value) in enumerate(zip(shapes, dtypes, values)):
with self.test_session(graph=tf.Graph())... | Creates checkpoints for previous trials and returns num created. | _create_previous_trials | python | google/model_search | model_search/meta/transfer_learning_test.py | https://github.com/google/model_search/blob/master/model_search/meta/transfer_learning_test.py | Apache-2.0 |
def __init__(self,
phoenix_spec,
study_name,
study_owner,
optimization_goal="minimize",
optimization_metric="loss",
connection_config=None):
"""Initializes a new MLMD connection instance.
Args:
phoenix_spec: Phoenix... | Initializes a new MLMD connection instance.
Args:
phoenix_spec: PhoenixSpec proto.
study_name: The name of the study.
study_owner: The owner (username) of the study.
optimization_goal: minimize or maximize (string).
optimization_metric: what metric are we optimizing (string).
co... | __init__ | python | google/model_search | model_search/metadata/ml_metadata_db.py | https://github.com/google/model_search/blob/master/model_search/metadata/ml_metadata_db.py | Apache-2.0 |
def get_best_k(trials,
k=1,
status_whitelist=None,
optimization_goal='minimize'):
"""Returns the top k trials sorted by objective_value.
Args:
trials: The trials (Trail objects) to sort and return the top_k of.
k: The top k trials to return. If k=1 we don't retu... | Returns the top k trials sorted by objective_value.
Args:
trials: The trials (Trail objects) to sort and return the top_k of.
k: The top k trials to return. If k=1 we don't return a list.
status_whitelist: list of statuses to whitelist. If None, we use all trials.
optimization_goal: string, minimize ... | get_best_k | python | google/model_search | model_search/metadata/trial.py | https://github.com/google/model_search/blob/master/model_search/metadata/trial.py | Apache-2.0 |
def __init__(self,
num_units,
memory_size=0,
rank=0,
use_bias=True,
activation=None,
feature_weights_initializer=None,
time_weights_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),... | Initializes SvdfCell.
Arguments:
num_units: int or long, the number of units in the layer.
memory_size: int or long, the size of the memory (i.e. every new inference
iteration we push a new memory entry, and remove the oldest one).
rank: int or long, the rank of the SVD approximation.
... | __init__ | python | google/model_search | model_search/ops/svdf_cell.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_cell.py | Apache-2.0 |
def __call__(self, inputs, state, scope=None):
"""SVDF Cell computation.
Arguments:
inputs: 2D Tensor, where the first dimension could be used for batching
purposes, and last dimension corresponds to the features. The size of
this last dimension determines the size of the feature filters.... | SVDF Cell computation.
Arguments:
inputs: 2D Tensor, where the first dimension could be used for batching
purposes, and last dimension corresponds to the features. The size of
this last dimension determines the size of the feature filters.
state: The state as of the last inference in th... | __call__ | python | google/model_search | model_search/ops/svdf_cell.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_cell.py | Apache-2.0 |
def _add_filter_image_summary(self, filters, name):
"""Adds image summaries for the given filter (an image per rank).
Arguments:
filters: A Tensor containing the filters. Expected shape: [rank *
num_units, filter_dim]. Thus, the tensor groups the rank filters for
each unit, and the functi... | Adds image summaries for the given filter (an image per rank).
Arguments:
filters: A Tensor containing the filters. Expected shape: [rank *
num_units, filter_dim]. Thus, the tensor groups the rank filters for
each unit, and the function will split them to generate an image per
rank. E... | _add_filter_image_summary | python | google/model_search | model_search/ops/svdf_cell.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_cell.py | Apache-2.0 |
def _runTest(self, num_units, memory_size, rank, inputs, use_bias, activation,
expected):
"""Executes SVDF test run.
Checks svdf produces the same outputs (activations/gradients) and
parameters.
Arguments:
num_units: int or long, the number of units in the layer.
memory_size... | Executes SVDF test run.
Checks svdf produces the same outputs (activations/gradients) and
parameters.
Arguments:
num_units: int or long, the number of units in the layer.
memory_size: int or long, the size of the SVDF cell memory.
rank: int or long, the rank of the SVD approximation.
... | _runTest | python | google/model_search | model_search/ops/svdf_cell_test.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_cell_test.py | Apache-2.0 |
def build(self, input_shape: List[int]):
"""Implements build interface for tf.keras.layers.Layer."""
# Sub-classes should check for input_shape and then call super.build.
self.num_features = input_shape[-1]
self.feature_kernel = self.add_weight(
shape=(self.num_features, self.num_filters),
... | Implements build interface for tf.keras.layers.Layer. | build | python | google/model_search | model_search/ops/svdf_conv.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_conv.py | Apache-2.0 |
def get_config(self) -> Dict[Text, Any]:
"""Configs of the model hparams for logging and debugging purposes."""
config = {
"units":
self.units,
"memory_size":
self.memory_size,
"rank":
self.rank,
"activation":
tf.keras.activations.s... | Configs of the model hparams for logging and debugging purposes. | get_config | python | google/model_search | model_search/ops/svdf_conv.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_conv.py | Apache-2.0 |
def call(self, inputs: tf.Tensor, training: Optional[bool] = None):
"""Implements call interface for tf.keras.layers.Layer."""
# Handle drop out.
if 0 < self.dropout < 1 and self._dropout_mask is not None:
self._dropout_mask = _generate_dropout_mask(
tf.keras.backend.ones_like(inputs), self.... | Implements call interface for tf.keras.layers.Layer. | call | python | google/model_search | model_search/ops/svdf_conv.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_conv.py | Apache-2.0 |
def _get_test_svdf_layer_weights():
"""Returns weights for an SvdfCell with following params.
(units=4, memory_size=3, rank=1, use_bias=True).
"""
return [
np.array([[-0.31614766, 0.37929568, 0.27584907, -0.36453721],
[-0.35801932, 0.22514193, 0.27241215, -0.06950231],
[... | Returns weights for an SvdfCell with following params.
(units=4, memory_size=3, rank=1, use_bias=True).
| _get_test_svdf_layer_weights | python | google/model_search | model_search/ops/svdf_conv_test.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_conv_test.py | Apache-2.0 |
def _get_test_svdf_expected_output():
"""Returns output of an svdf layer with the following params.
Note: the values are obtained from _get_svdf_output_using_numpy computation.
"""
return np.array([
[[-0.00300881, 0.00605831, 0.01394408, 0.00183136],
[-0.0082326, 0.0207185, 0.06872095, 0.0030723... | Returns output of an svdf layer with the following params.
Note: the values are obtained from _get_svdf_output_using_numpy computation.
| _get_test_svdf_expected_output | python | google/model_search | model_search/ops/svdf_conv_test.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_conv_test.py | Apache-2.0 |
def _get_svdf_output_using_numpy(input_values, weights):
"""Compute svdf output using numpy for expected values.
NOTE: Use this helper function as a way to verify computations in tensorflow.
This function assumes linear activation for svdf and projection.
Args:
input_values: ndarray (shape=[batch_size, seq... | Compute svdf output using numpy for expected values.
NOTE: Use this helper function as a way to verify computations in tensorflow.
This function assumes linear activation for svdf and projection.
Args:
input_values: ndarray (shape=[batch_size, sequence_length, input_dim]).
weights: A list of 3 ndarrays f... | _get_svdf_output_using_numpy | python | google/model_search | model_search/ops/svdf_conv_test.py | https://github.com/google/model_search/blob/master/model_search/ops/svdf_conv_test.py | Apache-2.0 |
def __init__(self,
phoenix_spec,
alpha=0.05,
degree=2,
n_mono=10,
min_for_regression=3,
num_random_samples=10000,
num_of_restarts=3,
seed=None,
debug_mode=False):
"""Initializes the... | Initializes the Harmonica instance.
Args:
phoenix_spec: PhoenixSpec proto.
alpha: The alpha of lasso solver (please read on lasso solver to
understand this constant. In a nutshell, this control regularization for
lasso. alpha equal zero means regular linear regression - however, try
... | __init__ | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def basis_function(self, t, k):
r"""Calculates fourier basis.
Args:
t: integer.
k: integer.
Returns:
Returns the following value:
\Phi_t(k) = e^{(2\pi i k)/len(self._block_indices)}
"""
value = cmath.exp(
2 * cmath.pi * complex(0, 1) * t * k / len(self._block_indice... | Calculates fourier basis.
Args:
t: integer.
k: integer.
Returns:
Returns the following value:
\Phi_t(k) = e^{(2\pi i k)/len(self._block_indices)}
| basis_function | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def translate_architecture_to_feature_assignment(self, architecture):
"""Translates the trial architecture to a categorical assignment."""
category_size = len(self._block_indices)
# TODO(b/172564129): Change to use architecture.size instead of _num_params
x_real = np.empty(self._num_params * category_si... | Translates the trial architecture to a categorical assignment. | translate_architecture_to_feature_assignment | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def batch_sample(self, trials):
"""Returns all previous trials results as assignments and loss."""
completed = trials
x = []
y = []
for trial in completed:
arc = architecture_utils.get_architecture(
architecture_utils.DirectoryHandler.trial_dir(trial))
# Returns two assignments... | Returns all previous trials results as assignments and loss. | batch_sample | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def _parse_variable_name(self, name):
"""Returns the indices that form the variable given the name."""
# Bias
if name == "1":
return []
# Names are of the form 'x1 x6 x8'
else:
variables = name.split(" ")
return [int(varname[1:]) for varname in variables] | Returns the indices that form the variable given the name. | _parse_variable_name | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def _extract_relevant_variables_indices(self, feature_extender, coefficients):
"""Returns a list of the relevant variables indices based on coeff."""
all_variable_names = feature_extender.get_feature_names()
relevant_variables = []
for i, coeff in enumerate(coefficients):
if coeff > 0:
rel... | Returns a list of the relevant variables indices based on coeff. | _extract_relevant_variables_indices | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def _get_good_architecture(self,
feature_extender,
num_samples,
coefficients,
relevant_variables=None):
"""Randomly samples architectures, predict loss, and return minimal.
Args:
feature_ex... | Randomly samples architectures, predict loss, and return minimal.
Args:
feature_extender: sklearn PolynomialFeatures extnder.
num_samples: the number of samples from the search space the function will
try before returning the minimal point. If the search space over the
relevant variable... | _get_good_architecture | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def get_suggestion(self, trials, hparams, my_trial_id=None, model_dir=None):
"""Suggests a new architecture for Phoenix using the harmonica model.
For details please see:
https://arxiv.org/pdf/1706.00764.pdf
Args:
trials: a list of Trial objects
hparams: The suggested hparams.
my_tri... | Suggests a new architecture for Phoenix using the harmonica model.
For details please see:
https://arxiv.org/pdf/1706.00764.pdf
Args:
trials: a list of Trial objects
hparams: The suggested hparams.
my_trial_id: integer - the trial id which is making the call.
model_dir: string - th... | get_suggestion | python | google/model_search | model_search/search/categorical_harmonica.py | https://github.com/google/model_search/blob/master/model_search/search/categorical_harmonica.py | Apache-2.0 |
def random(prob):
"""Returns True with probability `prob`.
Exploration controller to indicate it's time to take a random action.
Args:
prob: triggering probability. If prob > random, then returns True.
Raises:
ValueError: if prob is not bounded in [0, 1].
"""
# 1.00001 to guard against numerical ... | Returns True with probability `prob`.
Exploration controller to indicate it's time to take a random action.
Args:
prob: triggering probability. If prob > random, then returns True.
Raises:
ValueError: if prob is not bounded in [0, 1].
| random | python | google/model_search | model_search/search/common.py | https://github.com/google/model_search/blob/master/model_search/search/common.py | Apache-2.0 |
def write_fork_edge(model_dir, to_id, from_id):
"""Write an edge for the search tree graph.
Args:
model_dir: a string with the model directory.
to_id: the target trial id (int).
from_id: the trial we forked from (int).
"""
if model_dir is None or not model_dir:
return
if not tf.io.gfile.exis... | Write an edge for the search tree graph.
Args:
model_dir: a string with the model directory.
to_id: the target trial id (int).
from_id: the trial we forked from (int).
| write_fork_edge | python | google/model_search | model_search/search/common.py | https://github.com/google/model_search/blob/master/model_search/search/common.py | Apache-2.0 |
def encode_architecture(architecture, problem_type):
"""Encodes the architecture of strings into the np.array.
Args:
architecture: A list of strings of the architecture.
problem_type: The phoenix_spec.ProblemType.
Returns:
The np.array of the encoded architecture.
"""
architecture = [block_buil... | Encodes the architecture of strings into the np.array.
Args:
architecture: A list of strings of the architecture.
problem_type: The phoenix_spec.ProblemType.
Returns:
The np.array of the encoded architecture.
| encode_architecture | python | google/model_search | model_search/search/common.py | https://github.com/google/model_search/blob/master/model_search/search/common.py | Apache-2.0 |
def get_allowed_depth(num_completed_trials, depth_thresholds=None,
max_depth=20):
"""Returns the current allowed depth of the architecture."""
if not depth_thresholds:
depth_thresholds = _default_depth_thresholds(max_depth)
if len(depth_thresholds) > max_depth:
raise ValueError(
... | Returns the current allowed depth of the architecture. | get_allowed_depth | python | google/model_search | model_search/search/common.py | https://github.com/google/model_search/blob/master/model_search/search/common.py | Apache-2.0 |
def block_indices(phoenix_spec):
"""Returns a list of allowable BlockType enum values from a phoenix_spec."""
return [
block_builder.BlockType[block_type]
for block_type in phoenix_spec.blocks_to_use
] | Returns a list of allowable BlockType enum values from a phoenix_spec. | block_indices | python | google/model_search | model_search/search/common.py | https://github.com/google/model_search/blob/master/model_search/search/common.py | Apache-2.0 |
def choose_random_trial_and_get_architecture(trials):
"""Returns (architecture, trial) of a randomly chosen `trial`."""
idx = np.random.randint(0, len(trials))
chosen_trial = trials[idx]
architecture = architecture_utils.get_architecture(
architecture_utils.DirectoryHandler.trial_dir(chosen_trial))
retu... | Returns (architecture, trial) of a randomly chosen `trial`. | choose_random_trial_and_get_architecture | python | google/model_search | model_search/search/common.py | https://github.com/google/model_search/blob/master/model_search/search/common.py | Apache-2.0 |
def mutate_replace(architecture, new_block):
"""Replaces one random block with the chosen new block.
Returns a copy; input is not modified. The element to replace is chosen
uniformly at random. Special care is taken not to replace the FLATTEN block.
Args:
architecture: An np.ndarray of integers correspond... | Replaces one random block with the chosen new block.
Returns a copy; input is not modified. The element to replace is chosen
uniformly at random. Special care is taken not to replace the FLATTEN block.
Args:
architecture: An np.ndarray of integers corresponding to BlockType enum.
new_block: Integer valu... | mutate_replace | python | google/model_search | model_search/search/common.py | https://github.com/google/model_search/blob/master/model_search/search/common.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.