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 command_indices(self, cmd): """indices TABLE: Lists all indices on table TABLE """ if len(cmd)!=1: raise self.Error("indices takes one table name") self.push_output() self.header=False self.output=self.output_list try: self.process_sql...
indices TABLE: Lists all indices on table TABLE
command_indices
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_load(self, cmd): """load FILE ?ENTRY?: Loads a SQLite extension library Note: Extension loading may not be enabled in the SQLite library version you are using. Extensions are an easy way to add new functions and functionality. For a useful extension look at the bot...
load FILE ?ENTRY?: Loads a SQLite extension library Note: Extension loading may not be enabled in the SQLite library version you are using. Extensions are an easy way to add new functions and functionality. For a useful extension look at the bottom of https://sqlite.org/contri...
command_load
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_mode(self, cmd): """mode MODE ?TABLE?: Sets output mode to one of""" if len(cmd) in (1,2): w=cmd[0] if w=="tabs": w="list" m=getattr(self, "output_"+w, None) if w!="insert": if len(cmd)==2: ra...
mode MODE ?TABLE?: Sets output mode to one of
command_mode
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_nullvalue(self, cmd): """nullvalue STRING: Print STRING in place of null values This affects textual output modes like column and list and sets how SQL null values are shown. The default is a zero length string. Insert mode and dumps are not affected by this settin...
nullvalue STRING: Print STRING in place of null values This affects textual output modes like column and list and sets how SQL null values are shown. The default is a zero length string. Insert mode and dumps are not affected by this setting. You can use double quotes to supply a zer...
command_nullvalue
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_output(self, cmd): """output FILENAME: Send output to FILENAME (or stdout) If the FILENAME is stdout then output is sent to standard output from when the shell was started. The file is opened using the current encoding (change with .encoding command). """ # ...
output FILENAME: Send output to FILENAME (or stdout) If the FILENAME is stdout then output is sent to standard output from when the shell was started. The file is opened using the current encoding (change with .encoding command).
command_output
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_prompt(self, cmd): """prompt MAIN ?CONTINUE?: Changes the prompts for first line and continuation lines The default is to print 'sqlite> ' for the main prompt where you can enter a dot command or a SQL statement. If the SQL statement is complete (eg not ; terminated) then y...
prompt MAIN ?CONTINUE?: Changes the prompts for first line and continuation lines The default is to print 'sqlite> ' for the main prompt where you can enter a dot command or a SQL statement. If the SQL statement is complete (eg not ; terminated) then you are prompted for more using the...
command_prompt
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_read(self, cmd): """read FILENAME: Processes SQL and commands in FILENAME (or Python if FILENAME ends with .py) Treats the specified file as input (a mixture or SQL and/or dot commands). If the filename ends in .py then it is treated as Python code instead. For Pyt...
read FILENAME: Processes SQL and commands in FILENAME (or Python if FILENAME ends with .py) Treats the specified file as input (a mixture or SQL and/or dot commands). If the filename ends in .py then it is treated as Python code instead. For Python code the symbol 'shell' refers to th...
command_read
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_restore(self, cmd): """restore ?DB? FILE: Restore database from FILE into DB (default "main") Copies the contents of FILE to the current database (default "main"). The backup is done at the page level - SQLite copies the pages as is. There is no round trip through SQL code....
restore ?DB? FILE: Restore database from FILE into DB (default "main") Copies the contents of FILE to the current database (default "main"). The backup is done at the page level - SQLite copies the pages as is. There is no round trip through SQL code.
command_restore
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_schema(self, cmd): """schema ?TABLE? [TABLE...]: Shows SQL for table If you give one or more tables then their schema is listed (including indices). If you don't specify any then all schemas are listed. TABLE is a like pattern so you can % for wildcards. """...
schema ?TABLE? [TABLE...]: Shows SQL for table If you give one or more tables then their schema is listed (including indices). If you don't specify any then all schemas are listed. TABLE is a like pattern so you can % for wildcards.
command_schema
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_separator(self, cmd): """separator STRING: Change separator for output mode and .import You can use quotes and backslashes. For example to set the separator to space tab space you can use: .separator " \\t " The setting is automatically changed when you switch t...
separator STRING: Change separator for output mode and .import You can use quotes and backslashes. For example to set the separator to space tab space you can use: .separator " \t " The setting is automatically changed when you switch to csv or tabs output mode. You should...
command_separator
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_show(self, cmd): """show: Show the current values for various settings.""" if len(cmd)>1: raise self.Error("show takes at most one parameter") if len(cmd): what=cmd[0] if what not in self._shows: raise self.Error("Unknown show: '%s'...
show: Show the current values for various settings.
command_show
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_tables(self, cmd): """tables ?PATTERN?: Lists names of tables matching LIKE pattern This also returns views. """ self.push_output() self.output=self.output_list self.header=False try: if len(cmd)==0: cmd=['%'] ...
tables ?PATTERN?: Lists names of tables matching LIKE pattern This also returns views.
command_tables
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_timeout(self, cmd): """timeout MS: Try opening locked tables for MS milliseconds If a database is locked by another process SQLite will keep retrying. This sets how many thousandths of a second it will keep trying for. If you supply zero or a negative number then a...
timeout MS: Try opening locked tables for MS milliseconds If a database is locked by another process SQLite will keep retrying. This sets how many thousandths of a second it will keep trying for. If you supply zero or a negative number then all busy handlers are disabled.
command_timeout
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_timer(self, cmd): """timer ON|OFF: Control printing of time and resource usage after each query The values displayed are in seconds when shown as floating point or an absolute count. Only items that have changed since starting the query are shown. On non-Windows platforms ...
timer ON|OFF: Control printing of time and resource usage after each query The values displayed are in seconds when shown as floating point or an absolute count. Only items that have changed since starting the query are shown. On non-Windows platforms considerably more information can...
command_timer
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def command_width(self, cmd): """width NUM NUM ...: Set the column widths for "column" mode In "column" output mode, each column is a fixed width with values truncated to fit. Specify new widths using this command. Use a negative number to right justify and zero for default column wid...
width NUM NUM ...: Set the column widths for "column" mode In "column" output mode, each column is a fixed width with values truncated to fit. Specify new widths using this command. Use a negative number to right justify and zero for default column width.
command_width
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def _terminal_width(self): """Works out the terminal width which is used for word wrapping some output (eg .help)""" try: if sys.platform=="win32": import ctypes, struct h=ctypes.windll.kernel32.GetStdHandle(-12) # -12 is stderr buf=cty...
Works out the terminal width which is used for word wrapping some output (eg .help)
_terminal_width
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def push_output(self): """Saves the current output settings onto a stack. See :meth:`pop_output` for more details as to why you would use this.""" o={} for k in "separator", "header", "nullvalue", "output", "widths", "truncate": o[k]=getattr(self, k) self._ou...
Saves the current output settings onto a stack. See :meth:`pop_output` for more details as to why you would use this.
push_output
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def pop_output(self): """Restores most recently pushed output. There are many output parameters such as nullvalue, mode (list/tcl/html/insert etc), column widths, header etc. If you temporarily need to change some settings then :meth:`push_output`, change the settings and then ...
Restores most recently pushed output. There are many output parameters such as nullvalue, mode (list/tcl/html/insert etc), column widths, header etc. If you temporarily need to change some settings then :meth:`push_output`, change the settings and then pop the old ones back. ...
pop_output
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def _append_input_description(self): """When displaying an error in :meth:`handle_exception` we want to give context such as when the commands being executed came from a .read command (which in turn could execute another .read). """ if self.interactive: return...
When displaying an error in :meth:`handle_exception` we want to give context such as when the commands being executed came from a .read command (which in turn could execute another .read).
_append_input_description
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def fixup_backslashes(self, s): """Implements the various backlash sequences in s such as turning backslash t into a tab. This function is needed because shlex does not do it for us. """ if "\\" not in s: return s # See the resolve_backslashes function in SQLite shell so...
Implements the various backlash sequences in s such as turning backslash t into a tab. This function is needed because shlex does not do it for us.
fixup_backslashes
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def write(self, dest, text): """Writes text to dest. dest will typically be one of self.stdout or self.stderr.""" # ensure text is unicode to catch codeset issues here if type(text)!=unicode: text=unicode(text) try: dest.write(text) ...
Writes text to dest. dest will typically be one of self.stdout or self.stderr.
write
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def getline(self, prompt=""): """Returns a single line of input (may be incomplete SQL) from self.stdin. If EOF is reached then return None. Do not include trailing newline in return. """ self.stdout.flush() self.stderr.flush() try: if self.interacti...
Returns a single line of input (may be incomplete SQL) from self.stdin. If EOF is reached then return None. Do not include trailing newline in return.
getline
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def getcompleteline(self): """Returns a complete input. For dot commands it will be one line. For SQL statements it will be as many as is necessary to have a :meth:`~apsw.complete` statement (ie semicolon terminated). Returns None on end of file.""" try: sel...
Returns a complete input. For dot commands it will be one line. For SQL statements it will be as many as is necessary to have a :meth:`~apsw.complete` statement (ie semicolon terminated). Returns None on end of file.
getcompleteline
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def handle_interrupt(self): """Deal with keyboard interrupt (typically Control-C). It will :meth:`~Connection.interrupt` the database and print"^C" if interactive.""" self.db.interrupt() if not self.bail and self.interactive: self.write(self.stderr, "^C\n") retur...
Deal with keyboard interrupt (typically Control-C). It will :meth:`~Connection.interrupt` the database and print"^C" if interactive.
handle_interrupt
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def process_complete_line(self, command): """Given some text will call the appropriate method to process it (eg :meth:`process_sql` or :meth:`process_command`)""" try: if len(command.strip())==0: return if command[0]==".": self.process_comm...
Given some text will call the appropriate method to process it (eg :meth:`process_sql` or :meth:`process_command`)
process_complete_line
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def push_input(self): """Saves the current input parameters to a stack. See :meth:`pop_input`.""" d={} for i in "interactive", "stdin", "input_line_number": d[i]=getattr(self, i) self._input_stack.append(d)
Saves the current input parameters to a stack. See :meth:`pop_input`.
push_input
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def pop_input(self): """Restore most recently pushed input parameters (interactive, self.stdin, linenumber etc). Use this if implementing a command like read. Push the current input, read the file and then pop the input to go back to before. """ assert(len(self._input_s...
Restore most recently pushed input parameters (interactive, self.stdin, linenumber etc). Use this if implementing a command like read. Push the current input, read the file and then pop the input to go back to before.
pop_input
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def complete(self, token, state): """Return a possible completion for readline This function is called with state starting at zero to get the first completion, then one/two/three etc until you return None. The best implementation is to generate the list when state==0, save it, ...
Return a possible completion for readline This function is called with state starting at zero to get the first completion, then one/two/three etc until you return None. The best implementation is to generate the list when state==0, save it, and provide members on each increase. ...
complete
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def _get_prev_tokens(self, line, end): "Returns the tokens prior to pos end in the line" return re.findall(r'"?\w+"?', line[:end])
Returns the tokens prior to pos end in the line
_get_prev_tokens
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def complete_sql(self, line, token, beg, end): """Provide some completions for SQL :param line: The current complete input line :param token: The word readline is looking for matches :param beg: Integer offset of token in line :param end: Integer end of token in line :re...
Provide some completions for SQL :param line: The current complete input line :param token: The word readline is looking for matches :param beg: Integer offset of token in line :param end: Integer end of token in line :return: A list of completions, or an empty list if none ...
complete_sql
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def complete_command(self, line, token, beg, end): """Provide some completions for dot commands :param line: The current complete input line :param token: The word readline is looking for matches :param beg: Integer offset of token in line :param end: Integer end of token in lin...
Provide some completions for dot commands :param line: The current complete input line :param token: The word readline is looking for matches :param beg: Integer offset of token in line :param end: Integer end of token in line :return: A list of completions, or an empty list if ...
complete_command
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def get_resource_usage(self): """Return a dict of various numbers (ints or floats). The .timer command shows the difference between before and after results of what this returns by calling :meth:`display_timing`""" if sys.platform=="win32": import ctypes, time, platform ...
Return a dict of various numbers (ints or floats). The .timer command shows the difference between before and after results of what this returns by calling :meth:`display_timing`
get_resource_usage
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def display_timing(self, b4, after): """Writes the difference between b4 and after to self.stderr. The data is dictionaries returned from :meth:`get_resource_usage`.""" v=list(b4.keys()) for i in after: if i not in v: v.append(i) v.sort() ...
Writes the difference between b4 and after to self.stderr. The data is dictionaries returned from :meth:`get_resource_usage`.
display_timing
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def main(): # Docstring must start on second line so dedenting works correctly """ Call this to run the interactive shell. It automatically passes in sys.argv[1:] and exits Python when done. """ try: s=Shell() _,_,cmds=s.process_args(sys.argv[1:]) if len(cmds)==0: ...
Call this to run the interactive shell. It automatically passes in sys.argv[1:] and exits Python when done.
main
python
plasticityai/magnitude
pymagnitude/third_party/_apsw/tools/shell.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py
MIT
def system_with_status_and_output( command, attach_env=True, should_silence_err=False, exit_with_error_message=None, _stdout=PIPE): """Runs a system command with various options and returns the status of the command and the output of the command. """ if should_silence_err: stderr...
Runs a system command with various options and returns the status of the command and the output of the command.
system_with_status_and_output
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/setup.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/setup.py
MIT
def system_with_output( command, attach_env=True, should_silence_err=False, exit_with_error_message=None): """Runs a system command with various options and returns the output of the command. """ return system_with_status_and_output( command, attach_env, should_silence_err, exit_...
Runs a system command with various options and returns the output of the command.
system_with_output
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/setup.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/setup.py
MIT
def _iterdump(connection): """ Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method,...
Returns an iterator to the dump of the database in an SQL text format. Used to produce an SQL dump of the database. Useful to save an in-memory database for later restoration. This function should not be called directly but instead called from the Connection method, iterdump().
_iterdump
python
plasticityai/magnitude
pymagnitude/third_party/_pysqlite/lib/dump.py
https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/lib/dump.py
MIT
def get_size(obj, seen=None): """Recursively finds size of objects Source: https://goshippo.com/blog/measure-real-size-any-python-object/ """ size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: return 0 # Important mark as seen *...
Recursively finds size of objects Source: https://goshippo.com/blog/measure-real-size-any-python-object/
get_size
python
plasticityai/magnitude
tests/benchmark.py
https://github.com/plasticityai/magnitude/blob/master/tests/benchmark.py
MIT
def get_channel_dim(input_tensor, data_format='INVALID'): """Returns the number of channels in the input tensor.""" shape = input_tensor.get_shape().as_list() assert data_format != 'INVALID' assert len(shape) == 4 if data_format == 'NHWC': return int(shape[3]) elif data_format == 'NCHW': return int(...
Returns the number of channels in the input tensor.
get_channel_dim
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds a block for phoenix. Args: input_tensors: A list of input tensors. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: T...
Builds a block for phoenix. Args: input_tensors: A list of input tensors. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: The training HParams. Returns: output_tensors: A list of the output tensors....
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def is_input_order_important(self): """Is the order of the entries in the input tensor important. Returns: A bool specifying if the order of the entries in the input is important. Examples where the order is important: Input for a cnn layer. (e.g., pixels an image). Examples when the order is...
Is the order of the entries in the input tensor important. Returns: A bool specifying if the order of the entries in the input is important. Examples where the order is important: Input for a cnn layer. (e.g., pixels an image). Examples when the order is not important: Input for a dense lay...
is_input_order_important
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def __init__(self, max_output_size=100, max_number_of_parameters=None, apply_batch_norm=False, residual_connection_type=None, **kwargs): """Initializes a new FullyConnectedBlock instance. Args: max_output_size: The maximum number ...
Initializes a new FullyConnectedBlock instance. Args: max_output_size: The maximum number of output neurons. max_number_of_parameters: The maximum number of parameters allowed. apply_batch_norm: Whether to apply batch normalization to the layer. residual_connection_type: The ResidualConnect...
__init__
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def _add_residual_connection(self, input_tensor, output_tensor): """Creates the residual connection between the input and the output.""" if self._residual_connection_type == ResidualConnectionType.NONE: return output_tensor in_shape = input_tensor.shape[-1] out_shape = output_tensor.shape[-1] ...
Creates the residual connection between the input and the output.
_add_residual_connection
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Applies 2d max pooling on the input tensor.""" input_tensor = input_tensors[-1] if input_tensor.get_shape().as_list()[2] < self._pool_size: return input_tensors max_pool = tf.keras.layers.MaxPool2D( pool_siz...
Applies 2d max pooling on the input tensor.
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Returns a ReLU activated output of a residual unit with 2 sub layers.""" input_tensor = input_tensors[-1] net1 = tf.keras.layers.Conv2D( get_channel_dim(input_tensor), kernel_size=self._kernel_size, nam...
Returns a ReLU activated output of a residual unit with 2 sub layers.
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Custom (wide) convolution block with some pooling.""" # Guard so that we won't have zero channels input_tensor = input_tensors[-1] if get_channel_dim(input_tensor) < 6: return input_tensors reduced = tf.keras.la...
Custom (wide) convolution block with some pooling.
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds a basic rnn block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: ...
Builds a basic rnn block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: hparams for the build. Returns: output tensor
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds a one dimensional convolutional block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the ba...
Builds a one dimensional convolutional block. Args: input_tensors: A tf.Tensor with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: hparams for the build. Returns: output tensor
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def block_build(self, input_tensors, is_training, lengths=None, hparams=None): """Builds as LSTM block. Args: input_tensors: A list of tf.Tensors with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hpar...
Builds as LSTM block. Args: input_tensors: A list of tf.Tensors with the input. is_training: Whether we are training. Used for regularization. lengths: The lengths of the input sequences in the batch. hparams: hparams for the build. Returns: output tensor
block_build
python
google/model_search
model_search/block.py
https://github.com/google/model_search/blob/master/model_search/block.py
Apache-2.0
def search_space(blocks_to_use=None): """Returns required search space for all blocks.""" search_space = ms_hparameters.Hyperparameters() for block_type in BlockType: if block_type == BlockType.EMPTY_BLOCK: continue if blocks_to_use is None or block_type.name in blocks_to_use: ta...
Returns required search space for all blocks.
search_space
python
google/model_search
model_search/block_builder.py
https://github.com/google/model_search/blob/master/model_search/block_builder.py
Apache-2.0
def replay_is_training_a_tower(self, my_id): """Returns True if we are training a new tower in a replay run. Example: 1. In adaptive ensembling, every trial is training one new tower, so the return value is always True. 2. In a non-adaptive ensembling, every trial except the last one is ...
Returns True if we are training a new tower in a replay run. Example: 1. In adaptive ensembling, every trial is training one new tower, so the return value is always True. 2. In a non-adaptive ensembling, every trial except the last one is training a new tower, whereas the last trial just e...
replay_is_training_a_tower
python
google/model_search
model_search/controller.py
https://github.com/google/model_search/blob/master/model_search/controller.py
Apache-2.0
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 _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