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 replay_is_importing_towers(self, my_id):
"""Returns true if we are importing a tower in this replay trial.
Examples:
1. For adaptive ensembling, we import towers for every trial with id
greater than 1.
2. For non-adaptive ensembling, we import towers only in the last trial.
Args:
... | Returns true if we are importing a tower in this replay trial.
Examples:
1. For adaptive ensembling, we import towers for every trial with id
greater than 1.
2. For non-adaptive ensembling, we import towers only in the last trial.
Args:
my_id: trial id.
Returns:
True if we a... | replay_is_importing_towers | python | google/model_search | model_search/controller.py | https://github.com/google/model_search/blob/master/model_search/controller.py | Apache-2.0 |
def _return_generators(generators):
"""Sets the number of towers to zero when generator isn't used."""
for generator_name in base_tower_generator.ALL_GENERATORS:
if generator_name not in generators.keys():
architecture_utils.set_number_of_towers(generator_name, 0)
return generators | Sets the number of towers to zero when generator isn't used. | _return_generators | python | google/model_search | model_search/controller.py | https://github.com/google/model_search/blob/master/model_search/controller.py | Apache-2.0 |
def get_generators(self, my_id, all_trials):
"""Returns the `Dict` of generators that need to be triggered.
Args:
my_id: an int with the current trial id.
all_trials: a list of metadata.trial.Trial protos with all information in
the current study.
Returns:
A dict of generator nam... | Returns the `Dict` of generators that need to be triggered.
Args:
my_id: an int with the current trial id.
all_trials: a list of metadata.trial.Trial protos with all information in
the current study.
Returns:
A dict of generator names as keys and GeneratorWithTrials as values.
| get_generators | python | google/model_search | model_search/controller.py | https://github.com/google/model_search/blob/master/model_search/controller.py | Apache-2.0 |
def bundle_logits(self, priors_logits_specs, search_logits_specs,
logits_dimension):
"""Bundles the priors and the search candidate into an ensemble."""
all_specs = priors_logits_specs + search_logits_specs
assert all_specs, "Got no logits specs from both generators."
with tf.compa... | Bundles the priors and the search candidate into an ensemble. | bundle_logits | python | google/model_search | model_search/ensembler.py | https://github.com/google/model_search/blob/master/model_search/ensembler.py | Apache-2.0 |
def as_text(bytes_or_text, encoding='utf-8'):
"""Converts any string-like python input types to unicode.
Returns the input as a unicode string. Uses utf-8 encoding for text
by default.
Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for decoding un... | Converts any string-like python input types to unicode.
Returns the input as a unicode string. Uses utf-8 encoding for text
by default.
Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for decoding unicode.
Returns:
A `unicode` (Python 2) or `s... | as_text | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def as_bytes(bytes_or_text, encoding='utf-8'):
"""Converts `bytearray`, `bytes`, or unicode python input types to `bytes`.
Uses utf-8 encoding for text by default.
Args:
bytes_or_text: A `bytearray`, `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for encoding unicode.
... | Converts `bytearray`, `bytes`, or unicode python input types to `bytes`.
Uses utf-8 encoding for text by default.
Args:
bytes_or_text: A `bytearray`, `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for encoding unicode.
Returns:
A `bytes` object.
Raises:
TypeEr... | as_bytes | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def _parse_fail(name, var_type, value, values):
"""Helper function for raising a value error for bad assignment."""
raise ValueError(
'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' %
(name, var_type.__name__, value, values)) | Helper function for raising a value error for bad assignment. | _parse_fail | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def _process_scalar_value(name, parse_fn, var_type, m_dict, values,
results_dictionary):
"""Update results_dictionary with a scalar value.
Used to update the results_dictionary to be returned by parse_values when
encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".)
Mu... | Update results_dictionary with a scalar value.
Used to update the results_dictionary to be returned by parse_values when
encountering a clause with a scalar RHS (e.g. "s=5" or "arr[0]=5".)
Mutates results_dictionary.
Args:
name: Name of variable in assignment ("s" or "arr").
parse_fn: Function for p... | _process_scalar_value | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def _process_list_value(name, parse_fn, var_type, m_dict, values,
results_dictionary):
"""Update results_dictionary from a list of values.
Used to update results_dictionary to be returned by parse_values when
encountering a clause with a list RHS (e.g. "arr=[1,2,3]".)
Mutates results_... | Update results_dictionary from a list of values.
Used to update results_dictionary to be returned by parse_values when
encountering a clause with a list RHS (e.g. "arr=[1,2,3]".)
Mutates results_dictionary.
Args:
name: Name of variable in assignment ("arr").
parse_fn: Function for parsing individual... | _process_list_value | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def _cast_to_type_if_compatible(name, param_type, value):
"""Cast hparam to the provided type, if compatible.
Args:
name: Name of the hparam to be cast.
param_type: The type of the hparam.
value: The value to be cast, if compatible.
Returns:
The result of casting `value` to `param_type`.
Rais... | Cast hparam to the provided type, if compatible.
Args:
name: Name of the hparam to be cast.
param_type: The type of the hparam.
value: The value to be cast, if compatible.
Returns:
The result of casting `value` to `param_type`.
Raises:
ValueError: If the type of `value` is not compatible wi... | _cast_to_type_if_compatible | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def parse_values(values, type_map, ignore_unknown=False):
"""Parses hyperparameter values from a string into a python map.
`values` is a string containing comma-separated `name=value` pairs.
For each pair, the value of the hyperparameter named `name` is set to
`value`.
If a hyperparameter name appears multi... | Parses hyperparameter values from a string into a python map.
`values` is a string containing comma-separated `name=value` pairs.
For each pair, the value of the hyperparameter named `name` is set to
`value`.
If a hyperparameter name appears multiple times in `values`, a ValueError
is raised (e.g. 'a=1,a=2'... | parse_values | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def __init__(self, hparam_def=None, model_structure=None, **kwargs):
"""Create an instance of `HParams` from keyword arguments.
The keyword arguments specify name-values pairs for the hyperparameters.
The parameter types are inferred from the type of the values passed.
The parameter names are added as... | Create an instance of `HParams` from keyword arguments.
The keyword arguments specify name-values pairs for the hyperparameters.
The parameter types are inferred from the type of the values passed.
The parameter names are added as attributes of `HParams` object, so they
can be accessed directly with t... | __init__ | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def _init_from_proto(self, hparam_def):
"""Creates a new HParams from `HParamDef` protocol buffer.
Args:
hparam_def: `HParamDef` protocol buffer.
"""
assert isinstance(hparam_def, hparam_pb2.HParamDef)
for name, value in hparam_def.hparam.items():
kind = value.WhichOneof('kind')
i... | Creates a new HParams from `HParamDef` protocol buffer.
Args:
hparam_def: `HParamDef` protocol buffer.
| _init_from_proto | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def add_hparam(self, name, value):
"""Adds {name, value} pair to hyperparameters.
Args:
name: Name of the hyperparameter.
value: Value of the hyperparameter. Can be one of the following types:
int, float, string, int list, float list, or string list.
Raises:
ValueError: if one of... | Adds {name, value} pair to hyperparameters.
Args:
name: Name of the hyperparameter.
value: Value of the hyperparameter. Can be one of the following types:
int, float, string, int list, float list, or string list.
Raises:
ValueError: if one of the arguments is invalid.
| add_hparam | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def set_hparam(self, name, value):
"""Set the value of an existing hyperparameter.
This function verifies that the type of the value matches the type of the
existing hyperparameter.
Args:
name: Name of the hyperparameter.
value: New value of the hyperparameter.
Raises:
KeyError:... | Set the value of an existing hyperparameter.
This function verifies that the type of the value matches the type of the
existing hyperparameter.
Args:
name: Name of the hyperparameter.
value: New value of the hyperparameter.
Raises:
KeyError: If the hyperparameter doesn't exist.
... | set_hparam | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def del_hparam(self, name):
"""Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter.
"""
if hasattr(self, name):
delattr(self, name)
del self._hparam_types[name] | Removes the hyperparameter with key 'name'.
Does nothing if it isn't present.
Args:
name: Name of the hyperparameter.
| del_hparam | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def parse(self, values):
"""Override existing hyperparameter values, parsing new values from a string.
See parse_values for more detail on the allowed format for values.
Args:
values: String. Comma separated list of `name=value` pairs where 'value'
must follow the syntax described above.
... | Override existing hyperparameter values, parsing new values from a string.
See parse_values for more detail on the allowed format for values.
Args:
values: String. Comma separated list of `name=value` pairs where 'value'
must follow the syntax described above.
Returns:
The `HParams` ... | parse | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def override_from_dict(self, values_dict):
"""Override existing hyperparameter values, parsing new values from a dictionary.
Args:
values_dict: Dictionary of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_dict` doesn't exist.
... | Override existing hyperparameter values, parsing new values from a dictionary.
Args:
values_dict: Dictionary of name:value pairs.
Returns:
The `HParams` instance.
Raises:
KeyError: If a hyperparameter in `values_dict` doesn't exist.
ValueError: If `values_dict` cannot be parsed.
... | override_from_dict | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def to_json(self, indent=None, separators=None, sort_keys=False):
"""Serializes the hyperparameters into JSON.
Args:
indent: If a non-negative integer, JSON array elements and object members
will be pretty-printed with that indent level. An indent level of 0, or
negative, will only insert... | Serializes the hyperparameters into JSON.
Args:
indent: If a non-negative integer, JSON array elements and object members
will be pretty-printed with that indent level. An indent level of 0, or
negative, will only insert newlines. `None` (the default) selects the
most compact represen... | to_json | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def get(self, key, default=None):
"""Returns the value of `key` if it exists, else `default`."""
if key in self._hparam_types:
# Ensure that default is compatible with the parameter type.
if default is not None:
param_type, is_param_list = self._hparam_types[key]
type_str = 'list<%s>... | Returns the value of `key` if it exists, else `default`. | get | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def _get_kind_name(param_type, is_list):
"""Returns the field name given parameter type and is_list.
Args:
param_type: Data type of the hparam.
is_list: Whether this is a list.
Returns:
A string representation of the field name.
Raises:
ValueError: If parameter type is not rec... | Returns the field name given parameter type and is_list.
Args:
param_type: Data type of the hparam.
is_list: Whether this is a list.
Returns:
A string representation of the field name.
Raises:
ValueError: If parameter type is not recognized.
| _get_kind_name | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def to_proto(self, export_scope=None): # pylint: disable=unused-argument
"""Converts a `HParams` object to a `HParamDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `HParamDef` protocol buffer.
"""
hparam_proto = hparam_pb2.HParamDef()
... | Converts a `HParams` object to a `HParamDef` protocol buffer.
Args:
export_scope: Optional `string`. Name scope to remove.
Returns:
A `HParamDef` protocol buffer.
| to_proto | python | google/model_search | model_search/hparam.py | https://github.com/google/model_search/blob/master/model_search/hparam.py | Apache-2.0 |
def bundle_logits(self,
priors_logits_specs,
search_logits_specs,
logits_dimension=None):
"""Bundles the logits from the priors and the search candidate.
Args:
priors_logits_specs: List of LogitSpecs associated with the prior towers.
searc... | Bundles the logits from the priors and the search candidate.
Args:
priors_logits_specs: List of LogitSpecs associated with the prior towers.
search_logits_specs: List containing the LogitSpecs associated with the
search (new) tower. (Empty if there is no search tower.)
logits_dimension: T... | bundle_logits | python | google/model_search | model_search/logit_bundler.py | https://github.com/google/model_search/blob/master/model_search/logit_bundler.py | Apache-2.0 |
def make_regression_loss_fn():
"""Returns the Mean Squared Error loss_fn for regression."""
def _loss_fn(labels, logits, weights=1.0):
return tf.compat.v1.losses.mean_squared_error(
labels=labels,
predictions=logits,
weights=weights,
reduction=tf.compat.v1.losses.Reduction.SUM_O... | Returns the Mean Squared Error loss_fn for regression. | make_regression_loss_fn | python | google/model_search | model_search/loss_fns.py | https://github.com/google/model_search/blob/master/model_search/loss_fns.py | Apache-2.0 |
def make_regression_absolute_difference_loss_fn():
"""Returns the Mean Average Error loss_fn for regression."""
def _loss_fn(labels, logits, weights=1.0):
return tf.compat.v1.losses.absolute_difference(
labels=labels,
predictions=logits,
weights=weights,
reduction=tf.compat.v1.l... | Returns the Mean Average Error loss_fn for regression. | make_regression_absolute_difference_loss_fn | python | google/model_search | model_search/loss_fns.py | https://github.com/google/model_search/blob/master/model_search/loss_fns.py | Apache-2.0 |
def make_regression_logarithmic_loss_fn():
"""Returns Mean Squared Logarithmic Error loss_fn for regression."""
def _loss_fn(labels, logits, weights=1.0):
return tf.compat.v1.losses.mean_squared_error(
labels=tf.math.log1p(tf.nn.relu(labels)),
predictions=logits,
weights=weights,
... | Returns Mean Squared Logarithmic Error loss_fn for regression. | make_regression_logarithmic_loss_fn | python | google/model_search | model_search/loss_fns.py | https://github.com/google/model_search/blob/master/model_search/loss_fns.py | Apache-2.0 |
def make_accuracy_metric_fn(label_vocabulary=None):
"""Makes a metric_fn for accuracy from an optional label_vocabulary.
Args:
label_vocabulary: A 1-D string Tensor or string list (in the single task
setup); or a dictionary mapping string keys to those (in the multi task
setup). The string keys cor... | Makes a metric_fn for accuracy from an optional label_vocabulary.
Args:
label_vocabulary: A 1-D string Tensor or string list (in the single task
setup); or a dictionary mapping string keys to those (in the multi task
setup). The string keys correspond to the task name, allowing different
tasks ... | make_accuracy_metric_fn | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def _metric_fn(labels, predictions, weights=None):
"""Metrics for tensorboard.
Args:
labels: A int64 Tensor or a string Tensor; or a dictionary mapping task
names (strings) to those. If a task name maps to a string Tensor, then
label_vocabulary needs to contain that task name as a key as ... | Metrics for tensorboard.
Args:
labels: A int64 Tensor or a string Tensor; or a dictionary mapping task
names (strings) to those. If a task name maps to a string Tensor, then
label_vocabulary needs to contain that task name as a key as well,
otherwise the task name would not have metri... | _metric_fn | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def _make_auc_metric_fn(curve, label_vocabulary):
"""Makes a metric_fn to compute AUC-ROC or AUC-PR.
Wraps around tf.metrics.auc(), so that it is easier to keep track of the
metric name with the string key. This only works in the single-task
binary-classification setup.
Args:
curve: "ROC" or "PR".
l... | Makes a metric_fn to compute AUC-ROC or AUC-PR.
Wraps around tf.metrics.auc(), so that it is easier to keep track of the
metric name with the string key. This only works in the single-task
binary-classification setup.
Args:
curve: "ROC" or "PR".
label_vocabulary: A 1-D string Tensor or string list. If... | _make_auc_metric_fn | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def _metric_fn(labels, predictions, weights=None):
"""Metrics for tensorboard.
Args:
labels: A 1-D Tensor castable to bool, where True means that the label for
that instance is class 1, and False means that the label for that
instance is class 0.
predictions: A dictionary mapping st... | Metrics for tensorboard.
Args:
labels: A 1-D Tensor castable to bool, where True means that the label for
that instance is class 1, and False means that the label for that
instance is class 0.
predictions: A dictionary mapping strings to Tensors. This dictionary
contains a `pred... | _metric_fn | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def create_num_parameters_metric_fn(tower_name=None):
"""Makes the function to count the number of trainable parameters.
Args:
tower_name: The name of the tower that contains variables we want to count.
If it is None, then use all variables.
Returns:
A function that returns a dict with a single st... | Makes the function to count the number of trainable parameters.
Args:
tower_name: The name of the tower that contains variables we want to count.
If it is None, then use all variables.
Returns:
A function that returns a dict with a single string key `num_parameters`
that maps to a tuple containi... | create_num_parameters_metric_fn | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def _metric_fn(labels, predictions, weights=None):
"""Counts the number of trainable parameters.
Args:
labels: Unused.
predictions: Unused.
weights: Unused.
Returns:
dict with a single string key `num_parameters` that maps to a tuple
containing two int32 0-D Tensors, both con... | Counts the number of trainable parameters.
Args:
labels: Unused.
predictions: Unused.
weights: Unused.
Returns:
dict with a single string key `num_parameters` that maps to a tuple
containing two int32 0-D Tensors, both containing the number of trainable
parameters.
| _metric_fn | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def combine_metric_fns(metric_fn_list):
"""Returns a single metric_fn that combines the outputs of metric_fn_list.
Args:
metric_fn_list: A list of functions that each takes arguments `labels` and
`predictions` and returns a dictionary mapping string keys to (tensor,
update_op) tuples.
Returns:
... | Returns a single metric_fn that combines the outputs of metric_fn_list.
Args:
metric_fn_list: A list of functions that each takes arguments `labels` and
`predictions` and returns a dictionary mapping string keys to (tensor,
update_op) tuples.
Returns:
A dictionary mapping string keys to (tenso... | combine_metric_fns | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def _metric_fn(labels, predictions, weights=None):
"""Returns a dictionary mapping string to (tensor, update_op) tuples."""
metrics_dict = {}
for child_metric_fn in metric_fn_list:
metrics_dict.update(child_metric_fn(labels, predictions, weights))
return metrics_dict | Returns a dictionary mapping string to (tensor, update_op) tuples. | _metric_fn | python | google/model_search | model_search/metric_fns.py | https://github.com/google/model_search/blob/master/model_search/metric_fns.py | Apache-2.0 |
def _set_model_dir_for_run_config(model_dir=None):
"""ContextManager for overwriting environment configuration for RunConfig."""
old_tf_config_str = os.environ.get(_TF_CONFIG_ENV)
new_tf_config = (
copy.deepcopy(json.loads(old_tf_config_str)) if old_tf_config_str else {})
if model_dir is not None:
n... | ContextManager for overwriting environment configuration for RunConfig. | _set_model_dir_for_run_config | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def get_dataset_provider():
"""Helper function to get the data provider."""
logging.info("Getting the registered data provider")
# Reigstration API
data_providers = registry.lookup_all(ms_data.Provider)
if len(data_providers) == 1:
return data_providers[0]
# Registering more than one data provider
el... | Helper function to get the data provider. | get_dataset_provider | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def loss_and_metric_and_predictions_fn(provider):
"""Helper function to create loss and metric fns."""
metric_fn = None
loss_fn = None
predictions_fn = None
if getattr(provider, "get_metric_fn", None) is not None:
metric_fn = provider.get_metric_fn()
if getattr(provider, "get_loss_fn", None) is not None... | Helper function to create loss and metric fns. | loss_and_metric_and_predictions_fn | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def make_run_config(model_dir=None, use_tpu=False):
"""Makes a RunConfig object with FLAGS.
Args:
model_dir: string - the model directory - to be used in the tpu run config
only.
use_tpu: boolean indicating if to use tpu run config or not.
Returns:
tf.estimator.RunConfig: Run config.
Raises... | Makes a RunConfig object with FLAGS.
Args:
model_dir: string - the model directory - to be used in the tpu run config
only.
use_tpu: boolean indicating if to use tpu run config or not.
Returns:
tf.estimator.RunConfig: Run config.
Raises:
ValueError: If not exactly one of `save_checkpoints... | make_run_config | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def get_trial_dir(model_dir, tuner_id):
"""Helper function to get trial directory."""
tuner_dir = os.path.join(model_dir, tuner_id)
if not tf.io.gfile.exists(tuner_dir):
tf.io.gfile.makedirs(tuner_dir)
existing_trials = tf.io.gfile.listdir(tuner_dir)
if not existing_trials:
trial_dir = os.path.join(tu... | Helper function to get trial directory. | get_trial_dir | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def aggregate_initial_architecture(hparams):
"""Helper function to aggregate initial architecture into an array hparam."""
output = hparams.copy()
initial_architecture_size = len(
[hp for hp in hparams.keys() if hp.startswith("initial_architecture")])
output["initial_architecture"] = [
hparams["init... | Helper function to aggregate initial architecture into an array hparam. | aggregate_initial_architecture | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def run_parameterized_train_and_eval(phoenix_instance, oracle, tuner_id,
root_dir, max_trials, data_provider,
train_steps, eval_steps, batch_size):
"""Train, getting parameters from a tuner.
Args:
phoenix_instance: a phoenix.Phoenix obje... | Train, getting parameters from a tuner.
Args:
phoenix_instance: a phoenix.Phoenix object.
oracle: a keras_tuner oracle.
tuner_id: identifier of the tuner (integer).
root_dir: the root directory to save the models.
max_trials: the maximal number of trials allowed.
data_provider: The data provi... | run_parameterized_train_and_eval | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def run_keras_parameterized_train_and_eval(phoenix_instance, oracle,
data_provider):
"""Train, getting parameters from a tuner.
Args:
phoenix_instance: a phoenix.Phoenix object.
oracle: a keras_tuner oracle.
data_provider: The data provider object.
Returns:... | Train, getting parameters from a tuner.
Args:
phoenix_instance: a phoenix.Phoenix object.
oracle: a keras_tuner oracle.
data_provider: The data provider object.
Returns:
True if the tuner provided a trial to run, False if the tuner
has run out of trials.
| run_keras_parameterized_train_and_eval | python | google/model_search | model_search/oss_trainer_lib.py | https://github.com/google/model_search/blob/master/model_search/oss_trainer_lib.py | Apache-2.0 |
def aggregate_initial_architecture(hparams):
"""Helper function to aggregate initial architecture into an array hparam."""
output = hparams.copy()
initial_architecture_size = len(
[hp for hp in hparams.keys() if hp.startswith("initial_architecture_")])
if initial_architecture_size:
output["initial_arc... | Helper function to aggregate initial architecture into an array hparam. | aggregate_initial_architecture | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def _default_predictions_fn(logits,
mode=tf.estimator.ModeKeys.TRAIN,
temperature=1.0):
"""Converts logits to predictions dict. Assumes classification."""
new_logits = logits
if mode == tf.estimator.ModeKeys.PREDICT and temperature != 1.0:
assert tempera... | Converts logits to predictions dict. Assumes classification. | _default_predictions_fn | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def __init__(self,
phoenix_spec,
input_layer_fn,
study_owner,
study_name,
head=None,
logits_dimension=None,
label_vocabulary=None,
loss_fn=None,
metric_fn=None,
predictio... | Constructs a Phoenix instance.
Args:
phoenix_spec: A `PhoenixSpec` proto with the spec for the run.
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.
study_owner: A string holding... | __init__ | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def keras_compile(self, towers, hparams):
"""Compiles the keras model based on hparams."""
optimizer_args = dict()
# Learning rate
lr = hparams.learning_rate
if getattr(hparams, "exponential_decay_rate", None) is not None:
max_times = self._phoenix_spec.learning_spec.max_decay_times
ste... | Compiles the keras model based on hparams. | keras_compile | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def keras_model_builder(self,
hparams,
run_config=None,
is_training=None,
input_layer_fn=None,
compile_model=True):
"""Builds a keras model based on hparams."""
if compile_model:
... | Builds a keras model based on hparams. | keras_model_builder | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def model_fn(features, labels, mode, params):
"""Model function that wraps the model specified."""
self._metric_fn = self._user_specified_metric_fn
self._default_metric_fn_list = []
if self._logits_dimension >= 2:
self._default_metric_fn_list.append(
metric_fns.make_accuracy_... | Model function that wraps the model specified. | model_fn | python | google/model_search | model_search/phoenix.py | https://github.com/google/model_search/blob/master/model_search/phoenix.py | Apache-2.0 |
def _increment_global_step(self, train_op, train_steps, tower_name):
"""Increments the global step based on the tower size.
N.B. if the tower size does not divide evenly into the train_steps, it will
train for longer than required.
Args:
train_op: The train_op to execute before incrementing the ... | Increments the global step based on the tower size.
N.B. if the tower size does not divide evenly into the train_steps, it will
train for longer than required.
Args:
train_op: The train_op to execute before incrementing the global_step.
train_steps: The total number of steps to train for.
... | _increment_global_step | 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_estimator(self, run_config, hparams, train_steps):
"""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 ... | 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.
Returns:
Returns an `Estimator`.
Raises:
... | get_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_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 _default_predictions_fn(logits,
mode=tf.estimator.ModeKeys.TRAIN,
temperature=1.0):
"""Converts logits to predictions dict. Assumes classification."""
new_logits = logits
if mode == tf.estimator.ModeKeys.PREDICT and temperature != 1.0:
temp_const = t... | Converts logits to predictions dict. Assumes classification. | _default_predictions_fn | python | google/model_search | model_search/task_manager_test.py | https://github.com/google/model_search/blob/master/model_search/task_manager_test.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 restore_from_checkpoint(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.
... | 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... | restore_from_checkpoint | 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 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.