INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Provide the root module of a TF-like API for use within TensorBoard. By default this is equivalent to `import tensorflow as tf`, but it can be used in combination with //tensorboard/compat:tensorflow (to fall back to a stub TF API implementation if the real one is not available) or with //tensorboard/compat:no...
def tf(): """Provide the root module of a TF-like API for use within TensorBoard. By default this is equivalent to `import tensorflow as tf`, but it can be used in combination with //tensorboard/compat:tensorflow (to fall back to a stub TF API implementation if the real one is not available) or with //tensor...
Provide the root module of a TF-2.0 API for use within TensorBoard. Returns: The root module of a TF-2.0 API, if available. Raises: ImportError: if a TF-2.0 API is not available.
def tf2(): """Provide the root module of a TF-2.0 API for use within TensorBoard. Returns: The root module of a TF-2.0 API, if available. Raises: ImportError: if a TF-2.0 API is not available. """ # Import the `tf` compat API from this file and check if it's already TF 2.0. if tf.__version__.start...
Provide pywrap_tensorflow access in TensorBoard. pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow and needs to be imported using `from tensorflow.python import pywrap_tensorflow`. Therefore, we provide a separate accessor function for it here. NOTE: pywrap_tensorflow is not part of Tens...
def _pywrap_tensorflow(): """Provide pywrap_tensorflow access in TensorBoard. pywrap_tensorflow cannot be accessed from tf.python.pywrap_tensorflow and needs to be imported using `from tensorflow.python import pywrap_tensorflow`. Therefore, we provide a separate accessor function for it here. NOTE: pywrap...
Returns a summary proto buffer holding this experiment.
def create_experiment_summary(): """Returns a summary proto buffer holding this experiment.""" # Convert TEMPERATURE_LIST to google.protobuf.ListValue temperature_list = struct_pb2.ListValue() temperature_list.extend(TEMPERATURE_LIST) materials = struct_pb2.ListValue() materials.extend(HEAT_COEFFICIENTS.ke...
Runs a temperature simulation. This will simulate an object at temperature `initial_temperature` sitting at rest in a large room at temperature `ambient_temperature`. The object has some intrinsic `heat_coefficient`, which indicates how much thermal conductivity it has: for instance, metals have high thermal...
def run(logdir, session_id, hparams, group_name): """Runs a temperature simulation. This will simulate an object at temperature `initial_temperature` sitting at rest in a large room at temperature `ambient_temperature`. The object has some intrinsic `heat_coefficient`, which indicates how much thermal conduc...
Run simulations on a reasonable set of parameters. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins.
def run_all(logdir, verbose=False): """Run simulations on a reasonable set of parameters. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins. """ writer = tf.summary.FileWriter(logdir) writer.add_summary(create_experiment_s...
Return the registered filesystem for the given file.
def get_filesystem(filename): """Return the registered filesystem for the given file.""" filename = compat.as_str_any(filename) prefix = "" index = filename.find("://") if index >= 0: prefix = filename[:index] fs = _REGISTERED_FILESYSTEMS.get(prefix, None) if fs is None: rais...
Recursive directory tree generator for directories. Args: top: string, a Directory name topdown: bool, Traverse pre order if True, post order if False. onerror: optional handler for errors. Should be a function, it will be called with the error as argument. Rethrowing the error aborts the...
def walk(top, topdown=True, onerror=None): """Recursive directory tree generator for directories. Args: top: string, a Directory name topdown: bool, Traverse pre order if True, post order if False. onerror: optional handler for errors. Should be a function, it will be called with the ...
Reads contents of a file to a string. Args: filename: string, a path binary_mode: bool, read as binary if True, otherwise text size: int, number of bytes or characters to read, otherwise read all the contents of the file from the offset offset: in...
def read(self, filename, binary_mode=False, size=None, offset=None): """Reads contents of a file to a string. Args: filename: string, a path binary_mode: bool, read as binary if True, otherwise text size: int, number of bytes or characters to read, otherwise ...
Returns a list of files that match the given pattern(s).
def glob(self, filename): """Returns a list of files that match the given pattern(s).""" if isinstance(filename, six.string_types): return [ # Convert the filenames to string from bytes. compat.as_str_any(matching_filename) for matching_filenam...
Returns a list of entries contained within a directory.
def listdir(self, dirname): """Returns a list of entries contained within a directory.""" if not self.isdir(dirname): raise errors.NotFoundError(None, None, "Could not find directory") entries = os.listdir(compat.as_str_any(dirname)) entries = [compat.as_str_any(item) for it...
Returns file statistics for a given path.
def stat(self, filename): """Returns file statistics for a given path.""" # NOTE: Size of the file is given by .st_size as returned from # os.stat(), but we convert to .length try: len = os.stat(compat.as_bytes(filename)).st_size except OSError: raise erro...
Split an S3-prefixed URL into bucket and path.
def bucket_and_path(self, url): """Split an S3-prefixed URL into bucket and path.""" url = compat.as_str_any(url) if url.startswith("s3://"): url = url[len("s3://"):] idx = url.index("/") bucket = url[:idx] path = url[(idx + 1):] return bucket, path
Determines whether a path exists or not.
def exists(self, filename): """Determines whether a path exists or not.""" client = boto3.client("s3") bucket, path = self.bucket_and_path(filename) r = client.list_objects(Bucket=bucket, Prefix=path, Delimiter="/") if r.get("Contents") or r.get("CommonPrefixes"): ret...
Reads contents of a file to a string. Args: filename: string, a path binary_mode: bool, read as binary if True, otherwise text size: int, number of bytes or characters to read, otherwise read all the contents of the file from the offset offset: in...
def read(self, filename, binary_mode=False, size=None, offset=None): """Reads contents of a file to a string. Args: filename: string, a path binary_mode: bool, read as binary if True, otherwise text size: int, number of bytes or characters to read, otherwise ...
Returns a list of files that match the given pattern(s).
def glob(self, filename): """Returns a list of files that match the given pattern(s).""" # Only support prefix with * at the end and no ? in the string star_i = filename.find('*') quest_i = filename.find('?') if quest_i >= 0: raise NotImplementedError( ...
Returns whether the path is a directory or not.
def isdir(self, dirname): """Returns whether the path is a directory or not.""" client = boto3.client("s3") bucket, path = self.bucket_and_path(dirname) if not path.endswith("/"): path += "/" # This will now only retrieve subdir content r = client.list_objects(Bucket...
Returns a list of entries contained within a directory.
def listdir(self, dirname): """Returns a list of entries contained within a directory.""" client = boto3.client("s3") bucket, path = self.bucket_and_path(dirname) p = client.get_paginator("list_objects") if not path.endswith("/"): path += "/" # This will now only ret...
Returns file statistics for a given path.
def stat(self, filename): """Returns file statistics for a given path.""" # NOTE: Size of the file is given by ContentLength from S3, # but we convert to .length client = boto3.client("s3") bucket, path = self.bucket_and_path(filename) try: obj = client.head_o...
Determine the most specific context that we're in. Returns: _CONTEXT_COLAB: If in Colab with an IPython notebook context. _CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook context (e.g., from running `jupyter notebook` at the command line). _CONTEXT_NONE: Otherwise (e.g., b...
def _get_context(): """Determine the most specific context that we're in. Returns: _CONTEXT_COLAB: If in Colab with an IPython notebook context. _CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook context (e.g., from running `jupyter notebook` at the command line). _CONTEXT...
Launch and display a TensorBoard instance as if at the command line. Args: args_string: Command-line arguments to TensorBoard, to be interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0". Shell metacharacters are not supported: e.g., "--logdir 2>&1" will point the logdir at the literal...
def start(args_string): """Launch and display a TensorBoard instance as if at the command line. Args: args_string: Command-line arguments to TensorBoard, to be interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0". Shell metacharacters are not supported: e.g., "--logdir 2>&1" will po...
Format the elapsed time for the given TensorBoardInfo. Args: info: A TensorBoardInfo value. Returns: A human-readable string describing the time since the server described by `info` started: e.g., "2 days, 0:48:58".
def _time_delta_from_info(info): """Format the elapsed time for the given TensorBoardInfo. Args: info: A TensorBoardInfo value. Returns: A human-readable string describing the time since the server described by `info` started: e.g., "2 days, 0:48:58". """ delta_seconds = int(time.time()) - info....
Display a TensorBoard instance already running on this machine. Args: port: The port on which the TensorBoard server is listening, as an `int`, or `None` to automatically select the most recently launched TensorBoard. height: The height of the frame into which to render the TensorBoard UI, ...
def display(port=None, height=None): """Display a TensorBoard instance already running on this machine. Args: port: The port on which the TensorBoard server is listening, as an `int`, or `None` to automatically select the most recently launched TensorBoard. height: The height of the frame into ...
Internal version of `display`. Args: port: As with `display`. height: As with `display`. print_message: True to print which TensorBoard instance was selected for display (if applicable), or False otherwise. display_handle: If not None, an IPython display handle into which to render Tensor...
def _display(port=None, height=None, print_message=False, display_handle=None): """Internal version of `display`. Args: port: As with `display`. height: As with `display`. print_message: True to print which TensorBoard instance was selected for display (if applicable), or False otherwise. dis...
Display a TensorBoard instance in a Colab output frame. The Colab VM is not directly exposed to the network, so the Colab runtime provides a service worker tunnel to proxy requests from the end user's browser through to servers running on the Colab VM: the output frame may issue requests to https://localhost:<...
def _display_colab(port, height, display_handle): """Display a TensorBoard instance in a Colab output frame. The Colab VM is not directly exposed to the network, so the Colab runtime provides a service worker tunnel to proxy requests from the end user's browser through to servers running on the Colab VM: the ...
Print a listing of known running TensorBoard instances. TensorBoard instances that were killed uncleanly (e.g., with SIGKILL or SIGQUIT) may appear in this list even if they are no longer running. Conversely, this list may be missing some entries if your operating system's temporary directory has been cleared ...
def list(): """Print a listing of known running TensorBoard instances. TensorBoard instances that were killed uncleanly (e.g., with SIGKILL or SIGQUIT) may appear in this list even if they are no longer running. Conversely, this list may be missing some entries if your operating system's temporary directory ...
Check the path name to see if it is probably a TF Events file. Args: path: A file path to check if it is an event file. Raises: ValueError: If the path is an empty string. Returns: If path is formatted like a TensorFlowEventsFile.
def IsTensorFlowEventsFile(path): """Check the path name to see if it is probably a TF Events file. Args: path: A file path to check if it is an event file. Raises: ValueError: If the path is an empty string. Returns: If path is formatted like a TensorFlowEventsFile. """ if not path: rais...
Yields all files in the given directory. The paths are absolute.
def ListDirectoryAbsolute(directory): """Yields all files in the given directory. The paths are absolute.""" return (os.path.join(directory, path) for path in tf.io.gfile.listdir(directory))
Escapes the glob characters in a path. Python 3 has a glob.escape method, but python 2 lacks it, so we manually implement this method. Args: path: The absolute path to escape. Returns: The escaped path string.
def _EscapeGlobCharacters(path): """Escapes the glob characters in a path. Python 3 has a glob.escape method, but python 2 lacks it, so we manually implement this method. Args: path: The absolute path to escape. Returns: The escaped path string. """ drive, path = os.path.splitdrive(path) retu...
Recursively lists all files within the directory. This method does not list subdirectories (in addition to regular files), and the file paths are all absolute. If the directory does not exist, this yields nothing. This method does so by glob-ing deeper and deeper directories, ie foo/*, foo/*/*, foo/*/*/* an...
def ListRecursivelyViaGlobbing(top): """Recursively lists all files within the directory. This method does not list subdirectories (in addition to regular files), and the file paths are all absolute. If the directory does not exist, this yields nothing. This method does so by glob-ing deeper and deeper dire...
Walks a directory tree, yielding (dir_path, file_paths) tuples. For each of `top` and its subdirectories, yields a tuple containing the path to the directory and the path to each of the contained files. Note that unlike os.Walk()/tf.io.gfile.walk()/ListRecursivelyViaGlobbing, this does not list subdirectories...
def ListRecursivelyViaWalking(top): """Walks a directory tree, yielding (dir_path, file_paths) tuples. For each of `top` and its subdirectories, yields a tuple containing the path to the directory and the path to each of the contained files. Note that unlike os.Walk()/tf.io.gfile.walk()/ListRecursivelyViaGlob...
Obtains all subdirectories with events files. The order of the subdirectories returned is unspecified. The internal logic that determines order varies by scenario. Args: path: The path to a directory under which to find subdirectories. Returns: A tuple of absolute paths of all subdirectories each wit...
def GetLogdirSubdirectories(path): """Obtains all subdirectories with events files. The order of the subdirectories returned is unspecified. The internal logic that determines order varies by scenario. Args: path: The path to a directory under which to find subdirectories. Returns: A tuple of absol...
Write an audio summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A `Tensor` representing audio data with shape `[k, t, c]`, where `k` is the number of audio clips, `t` is the number of frames, ...
def audio(name, data, sample_rate, step=None, max_outputs=3, encoding=None, description=None): """Write an audio summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active nam...
Determines whether a health pill event contains bad values. A bad value is one of NaN, -Inf, or +Inf. Args: event: (`Event`) A `tensorflow.Event` proto from `DebugNumericSummary` ops. Returns: An instance of `NumericsAlert`, if bad values are found. `None`, if no bad values are found. Rais...
def extract_numerics_alert(event): """Determines whether a health pill event contains bad values. A bad value is one of NaN, -Inf, or +Inf. Args: event: (`Event`) A `tensorflow.Event` proto from `DebugNumericSummary` ops. Returns: An instance of `NumericsAlert`, if bad values are found. `No...
Obtain the first timestamp. Args: event_key: the type key of the sought events (e.g., constants.NAN_KEY). If None, includes all event type keys. Returns: First (earliest) timestamp of all the events of the given type (or all event types if event_key is None).
def first_timestamp(self, event_key=None): """Obtain the first timestamp. Args: event_key: the type key of the sought events (e.g., constants.NAN_KEY). If None, includes all event type keys. Returns: First (earliest) timestamp of all the events of the given type (or all event typ...
Obtain the last timestamp. Args: event_key: the type key of the sought events (e.g., constants.NAN_KEY). If None, includes all event type keys. Returns: Last (latest) timestamp of all the events of the given type (or all event types if event_key is None).
def last_timestamp(self, event_key=None): """Obtain the last timestamp. Args: event_key: the type key of the sought events (e.g., constants.NAN_KEY). If None, includes all event type keys. Returns: Last (latest) timestamp of all the events of the given type (or all event types if...
Creates a JSON-able representation of this object. Returns: A dictionary mapping key to EventTrackerDescription (which can be used to create event trackers).
def create_jsonable_history(self): """Creates a JSON-able representation of this object. Returns: A dictionary mapping key to EventTrackerDescription (which can be used to create event trackers). """ return {value_category_key: tracker.get_description() for (value_category_key, ...
Register an alerting numeric event. Args: numerics_alert: An instance of `NumericsAlert`.
def register(self, numerics_alert): """Register an alerting numeric event. Args: numerics_alert: An instance of `NumericsAlert`. """ key = (numerics_alert.device_name, numerics_alert.tensor_name) if key in self._data: self._data[key].add(numerics_alert) else: if len(self._data...
Get a report of offending device/tensor names. The report includes information about the device name, tensor name, first (earliest) timestamp of the alerting events from the tensor, in addition to counts of nan, positive inf and negative inf events. Args: device_name_filter: regex filter for dev...
def report(self, device_name_filter=None, tensor_name_filter=None): """Get a report of offending device/tensor names. The report includes information about the device name, tensor name, first (earliest) timestamp of the alerting events from the tensor, in addition to counts of nan, positive inf and neg...
Creates a JSON-able representation of this object. Returns: A dictionary mapping (device, tensor name) to JSON-able object representations of NumericsAlertHistory.
def create_jsonable_registry(self): """Creates a JSON-able representation of this object. Returns: A dictionary mapping (device, tensor name) to JSON-able object representations of NumericsAlertHistory. """ # JSON does not support tuples as keys. Only strings. Therefore, we store # the ...
Generate wave data of the given form. The provided function `wave_constructor` should accept a scalar tensor of type float32, representing the frequency (in Hz) at which to construct a wave, and return a tensor of shape [1, _samples(), `n`] representing audio data (for some number of channels `n`). Waves wi...
def run(logdir, run_name, wave_name, wave_constructor): """Generate wave data of the given form. The provided function `wave_constructor` should accept a scalar tensor of type float32, representing the frequency (in Hz) at which to construct a wave, and return a tensor of shape [1, _samples(), `n`] represent...
Emit a sine wave at the given frequency.
def sine_wave(frequency): """Emit a sine wave at the given frequency.""" xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1]) ts = xs / FLAGS.sample_rate return tf.sin(2 * math.pi * frequency * ts)
Emit a triangle wave at the given frequency.
def triangle_wave(frequency): """Emit a triangle wave at the given frequency.""" xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1]) ts = xs / FLAGS.sample_rate # # A triangle wave looks like this: # # /\ /\ # / \ / \ # \ / \ / # \/ ...
Emit two sine waves, in stereo at different octaves.
def bisine_wave(frequency): """Emit two sine waves, in stereo at different octaves.""" # # We can first our existing sine generator to generate two different # waves. f_hi = frequency f_lo = frequency / 2.0 with tf.name_scope('hi'): sine_hi = sine_wave(f_hi) with tf.name_scope('lo'): sine_lo = s...
Emit two sine waves with balance oscillating left and right.
def bisine_wahwah_wave(frequency): """Emit two sine waves with balance oscillating left and right.""" # # This is clearly intended to build on the bisine wave defined above, # so we can start by generating that. waves_a = bisine_wave(frequency) # # Then, by reversing axis 2, we swap the stereo channels. B...
Generate waves of the shapes defined above. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins
def run_all(logdir, verbose=False): """Generate waves of the shapes defined above. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins """ waves = [sine_wave, square_wave, triangle_wave, bisine_wave, bisine_wahwah_w...
Prepares (modifies in-place) the graph to be served to the front-end. For now, it supports filtering out attributes that are too large to be shown in the graph UI. Args: graph: The GraphDef proto message. limit_attr_size: Maximum allowed size in bytes, before the attribute is considered large. D...
def prepare_graph_for_ui(graph, limit_attr_size=1024, large_attrs_key='_too_large_attrs'): """Prepares (modifies in-place) the graph to be served to the front-end. For now, it supports filtering out attributes that are too large to be shown in the graph UI. Args: graph: The GraphD...
Returns a dict of all runs and tags and their data availabilities.
def info_impl(self): """Returns a dict of all runs and tags and their data availabilities.""" result = {} def add_row_item(run, tag=None): run_item = result.setdefault(run, { 'run': run, 'tags': {}, # A run-wide GraphDef of ops. 'run_graph': False}) tag_i...
Result of the form `(body, mime_type)`, or `None` if no graph exists.
def graph_impl(self, run, tag, is_conceptual, limit_attr_size=None, large_attrs_key=None): """Result of the form `(body, mime_type)`, or `None` if no graph exists.""" if is_conceptual: tensor_events = self._multiplexer.Tensors(run, tag) # Take the first event if there are multiple events written fro...
Result of the form `(body, mime_type)`, or `None` if no data exists.
def run_metadata_impl(self, run, tag): """Result of the form `(body, mime_type)`, or `None` if no data exists.""" try: run_metadata = self._multiplexer.RunMetadata(run, tag) except ValueError: # TODO(stephanwlee): Should include whether FE is fetching for v1 or v2 RunMetadata # so we can r...
Given a single run, return the graph definition in protobuf format.
def graph_route(self, request): """Given a single run, return the graph definition in protobuf format.""" run = request.args.get('run') tag = request.args.get('tag', '') conceptual_arg = request.args.get('conceptual', False) is_conceptual = True if conceptual_arg == 'true' else False if run is ...
Given a tag and a run, return the session.run() metadata.
def run_metadata_route(self, request): """Given a tag and a run, return the session.run() metadata.""" tag = request.args.get('tag') run = request.args.get('run') if tag is None: return http_util.Respond( request, 'query parameter "tag" is required', 'text/plain', 400) if run is None...
Returns the plugin, if possible. Args: context: The TBContext flags. Returns: A ProfilePlugin instance or None if it couldn't be loaded.
def load(self, context): """Returns the plugin, if possible. Args: context: The TBContext flags. Returns: A ProfilePlugin instance or None if it couldn't be loaded. """ try: # pylint: disable=g-import-not-at-top,unused-import import tensorflow # Available in TensorFlo...
Create a Keras model with the given hyperparameters. Args: hparams: A dict mapping hyperparameters in `HPARAMS` to values. seed: A hashable object to be used as a random seed (e.g., to construct dropout layers in the model). Returns: A compiled Keras model.
def model_fn(hparams, seed): """Create a Keras model with the given hyperparameters. Args: hparams: A dict mapping hyperparameters in `HPARAMS` to values. seed: A hashable object to be used as a random seed (e.g., to construct dropout layers in the model). Returns: A compiled Keras model. ""...
Run a training/validation session. Flags must have been parsed for this function to behave. Args: data: The data as loaded by `prepare_data()`. base_logdir: The top-level logdir to which to write summary data. session_id: A unique string ID for this session. group_id: The string ID of the session ...
def run(data, base_logdir, session_id, group_id, hparams): """Run a training/validation session. Flags must have been parsed for this function to behave. Args: data: The data as loaded by `prepare_data()`. base_logdir: The top-level logdir to which to write summary data. session_id: A unique string ...
Load and normalize data.
def prepare_data(): """Load and normalize data.""" ((x_train, y_train), (x_test, y_test)) = DATASET.load_data() x_train = x_train.astype("float32") x_test = x_test.astype("float32") x_train /= 255.0 x_test /= 255.0 return ((x_train, y_train), (x_test, y_test))
Perform random search over the hyperparameter space. Arguments: logdir: The top-level directory into which to write data. This directory should be empty or nonexistent. verbose: If true, print out each run's name as it begins.
def run_all(logdir, verbose=False): """Perform random search over the hyperparameter space. Arguments: logdir: The top-level directory into which to write data. This directory should be empty or nonexistent. verbose: If true, print out each run's name as it begins. """ data = prepare_data() rng...
Sample a value uniformly from a domain. Args: domain: An `IntInterval`, `RealInterval`, or `Discrete` domain. rng: A `random.Random` object; defaults to the `random` module. Raises: TypeError: If `domain` is not a known kind of domain. IndexError: If the domain is empty.
def sample_uniform(domain, rng): """Sample a value uniformly from a domain. Args: domain: An `IntInterval`, `RealInterval`, or `Discrete` domain. rng: A `random.Random` object; defaults to the `random` module. Raises: TypeError: If `domain` is not a known kind of domain. IndexError: If the domai...
A route that returns a JSON mapping between runs and PR curve data. Returns: Given a tag and a comma-separated list of runs (both stored within GET parameters), fetches a JSON object that maps between run name and objects containing data required for PR curves for that run. Runs that either ...
def pr_curves_route(self, request): """A route that returns a JSON mapping between runs and PR curve data. Returns: Given a tag and a comma-separated list of runs (both stored within GET parameters), fetches a JSON object that maps between run name and objects containing data required for PR ...
Creates the JSON object for the PR curves response for a run-tag combo. Arguments: runs: A list of runs to fetch the curves for. tag: The tag to fetch the curves for. Raises: ValueError: If no PR curves could be fetched for a run and tag. Returns: The JSON object for the PR curves...
def pr_curves_impl(self, runs, tag): """Creates the JSON object for the PR curves response for a run-tag combo. Arguments: runs: A list of runs to fetch the curves for. tag: The tag to fetch the curves for. Raises: ValueError: If no PR curves could be fetched for a run and tag. Retu...
Creates the JSON object for the tags route response. Returns: The JSON object for the tags route response.
def tags_impl(self): """Creates the JSON object for the tags route response. Returns: The JSON object for the tags route response. """ if self._db_connection_provider: # Read tags from the database. db = self._db_connection_provider() cursor = db.execute(''' SELECT ...
Creates the JSON object for the available time entries route response. Returns: The JSON object for the available time entries route response.
def available_time_entries_impl(self): """Creates the JSON object for the available time entries route response. Returns: The JSON object for the available time entries route response. """ result = {} if self._db_connection_provider: db = self._db_connection_provider() # For each ...
Determines whether this plugin is active. This plugin is active only if PR curve summary data is read by TensorBoard. Returns: Whether this plugin is active.
def is_active(self): """Determines whether this plugin is active. This plugin is active only if PR curve summary data is read by TensorBoard. Returns: Whether this plugin is active. """ if self._db_connection_provider: # The plugin is active if one relevant tag can be found in the data...
Converts a TensorEvent into a dict that encapsulates information on it. Args: event: The TensorEvent to convert. thresholds: An array of floats that ranges from 0 to 1 (in that direction and inclusive of 0 and 1). Returns: A JSON-able dictionary of PR curve data for 1 step.
def _process_tensor_event(self, event, thresholds): """Converts a TensorEvent into a dict that encapsulates information on it. Args: event: The TensorEvent to convert. thresholds: An array of floats that ranges from 0 to 1 (in that direction and inclusive of 0 and 1). Returns: A ...
Creates an entry for PR curve data. Each entry corresponds to 1 step. Args: step: The step. wall_time: The wall time. data_array: A numpy array of PR curve data stored in the summary format. thresholds: An array of floating point thresholds. Returns: A PR curve entry.
def _make_pr_entry(self, step, wall_time, data_array, thresholds): """Creates an entry for PR curve data. Each entry corresponds to 1 step. Args: step: The step. wall_time: The wall time. data_array: A numpy array of PR curve data stored in the summary format. thresholds: An array of fl...
Normalize a dict keyed by `HParam`s and/or raw strings. Args: hparams: A `dict` whose keys are `HParam` objects and/or strings representing hyperparameter names, and whose values are hyperparameter values. No two keys may have the same name. Returns: A `dict` whose keys are hyperparameter name...
def _normalize_hparams(hparams): """Normalize a dict keyed by `HParam`s and/or raw strings. Args: hparams: A `dict` whose keys are `HParam` objects and/or strings representing hyperparameter names, and whose values are hyperparameter values. No two keys may have the same name. Returns: A `di...
Create a top-level experiment summary describing this experiment. The resulting summary should be written to a log directory that encloses all the individual sessions' log directories. Analogous to the low-level `experiment_pb` function in the `hparams.summary` module.
def summary_pb(self): """Create a top-level experiment summary describing this experiment. The resulting summary should be written to a log directory that encloses all the individual sessions' log directories. Analogous to the low-level `experiment_pb` function in the `hparams.summary` module. ...
Generate a bunch of histogram data, and write it to logdir.
def run_all(logdir, verbose=False, num_summaries=400): """Generate a bunch of histogram data, and write it to logdir.""" del verbose tf.compat.v1.set_random_seed(0) k = tf.compat.v1.placeholder(tf.float32) # Make a normal distribution, with a shifting mean mean_moving_normal = tf.random.normal(shape=[100...
Parses and asserts a positive (>0) integer query parameter. Args: request: The Werkzeug Request object param_name: Name of the parameter. Returns: Param, or None, or -1 if parameter is not a positive integer.
def _parse_positive_int_param(request, param_name): """Parses and asserts a positive (>0) integer query parameter. Args: request: The Werkzeug Request object param_name: Name of the parameter. Returns: Param, or None, or -1 if parameter is not a positive integer. """ param = request.args.get(par...
Determines whether this plugin is active. This plugin is only active if any run has an embedding. Returns: Whether any run has embedding data to show in the projector.
def is_active(self): """Determines whether this plugin is active. This plugin is only active if any run has an embedding. Returns: Whether any run has embedding data to show in the projector. """ if not self.multiplexer: return False if self._is_active: # We have already det...
Adds a named column of metadata values. Args: column_name: Name of the column. column_values: 1D array/list/iterable holding the column values. Must be of length `num_points`. The i-th value corresponds to the i-th point. Raises: ValueError: If `column_values` is not 1D array, or o...
def add_column(self, column_name, column_values): """Adds a named column of metadata values. Args: column_name: Name of the column. column_values: 1D array/list/iterable holding the column values. Must be of length `num_points`. The i-th value corresponds to the i-th point. Raises: ...
Returns a map of run paths to `ProjectorConfig` protos.
def configs(self): """Returns a map of run paths to `ProjectorConfig` protos.""" run_path_pairs = list(self.run_paths.items()) self._append_plugin_asset_directories(run_path_pairs) # If there are no summary event files, the projector should still work, # treating the `logdir` as the model checkpoint...
Call `Reload` on every `EventAccumulator`.
def Reload(self): """Call `Reload` on every `EventAccumulator`.""" logger.info('Beginning EventMultiplexer.Reload()') self._reload_called = True # Build a list so we're safe even if the list of accumulators is modified # even while we're reloading. with self._accumulators_mutex: items = li...
Retrieve the histogram events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available for the given run. ...
def Histograms(self, run, tag): """Retrieve the histogram events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not a...
Retrieve the compressed histogram events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available for the giv...
def CompressedHistograms(self, run, tag): """Retrieve the compressed histogram events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found...
Retrieve the image events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available for the given run. Re...
def Images(self, run, tag): """Retrieve the image events associated with a run and tag. Args: run: A string name of the run for which values are retrieved. tag: A string name of the tag for which values are retrieved. Raises: KeyError: If the run is not found, or the tag is not available...
Write a histogram summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A `Tensor` of any shape. Must be castable to `float64`. step: Explicit `int64`-castable monotonic step value for this summary. If ...
def histogram(name, data, step=None, buckets=None, description=None): """Write a histogram summary. Arguments: name: A name for this summary. The summary tag used for TensorBoard will be this name prefixed by any active name scopes. data: A `Tensor` of any shape. Must be castable to `float64`. st...
Create a histogram summary protobuf. Arguments: tag: String tag for the summary. data: A `np.array` or array-like form of any shape. Must have type castable to `float`. buckets: Optional positive `int`. The output will have this many buckets, except in two edge cases. If there is no data, the...
def histogram_pb(tag, data, buckets=None, description=None): """Create a histogram summary protobuf. Arguments: tag: String tag for the summary. data: A `np.array` or array-like form of any shape. Must have type castable to `float`. buckets: Optional positive `int`. The output will have this ...
Makes recommended modifications to the environment. This functions changes global state in the Python process. Calling this function is a good idea, but it can't appropriately be called from library routines.
def setup_environment(): """Makes recommended modifications to the environment. This functions changes global state in the Python process. Calling this function is a good idea, but it can't appropriately be called from library routines. """ absl.logging.set_verbosity(absl.logging.WARNING) # The default ...
Opens stock TensorBoard web assets collection. Returns: Returns function that returns a newly opened file handle to zip file containing static assets for stock TensorBoard, or None if webfiles.zip could not be found. The value the callback returns must be closed. The paths inside the zip file are con...
def get_default_assets_zip_provider(): """Opens stock TensorBoard web assets collection. Returns: Returns function that returns a newly opened file handle to zip file containing static assets for stock TensorBoard, or None if webfiles.zip could not be found. The value the callback returns must be close...
Create a server factory that performs port scanning. This function returns a callable whose signature matches the specification of `TensorBoardServer.__init__`, using `cls` as an underlying implementation. It passes through `flags` unchanged except in the case that `flags.port is None`, in which case it repeat...
def with_port_scanning(cls): """Create a server factory that performs port scanning. This function returns a callable whose signature matches the specification of `TensorBoardServer.__init__`, using `cls` as an underlying implementation. It passes through `flags` unchanged except in the case that `flags.port...
Configures TensorBoard behavior via flags. This method will populate the "flags" property with an argparse.Namespace representing flag values parsed from the provided argv list, overridden by explicit flags from remaining keyword arguments. Args: argv: Can be set to CLI args equivalent to sys.ar...
def configure(self, argv=('',), **kwargs): """Configures TensorBoard behavior via flags. This method will populate the "flags" property with an argparse.Namespace representing flag values parsed from the provided argv list, overridden by explicit flags from remaining keyword arguments. Args: ...
Blocking main function for TensorBoard. This method is called by `tensorboard.main.run_main`, which is the standard entrypoint for the tensorboard command line program. The configure() method must be called first. Args: ignored_argv: Do not pass. Required for Abseil compatibility. Returns: ...
def main(self, ignored_argv=('',)): """Blocking main function for TensorBoard. This method is called by `tensorboard.main.run_main`, which is the standard entrypoint for the tensorboard command line program. The configure() method must be called first. Args: ignored_argv: Do not pass. Requir...
Python API for launching TensorBoard. This method is the same as main() except it launches TensorBoard in a separate permanent thread. The configure() method must be called first. Returns: The URL of the TensorBoard web server. :rtype: str
def launch(self): """Python API for launching TensorBoard. This method is the same as main() except it launches TensorBoard in a separate permanent thread. The configure() method must be called first. Returns: The URL of the TensorBoard web server. :rtype: str """ # Make it easy...
Write a TensorBoardInfo file and arrange for its cleanup. Args: server: The result of `self._make_server()`.
def _register_info(self, server): """Write a TensorBoardInfo file and arrange for its cleanup. Args: server: The result of `self._make_server()`. """ server_url = urllib.parse.urlparse(server.get_url()) info = manager.TensorBoardInfo( version=version.VERSION, start_time=int(ti...
Set a signal handler to gracefully exit on the given signal. When this process receives the given signal, it will run `atexit` handlers and then exit with `0`. Args: signal_number: The numeric code for the signal to handle, like `signal.SIGTERM`. signal_name: The human-readable signal ...
def _install_signal_handler(self, signal_number, signal_name): """Set a signal handler to gracefully exit on the given signal. When this process receives the given signal, it will run `atexit` handlers and then exit with `0`. Args: signal_number: The numeric code for the signal to handle, like ...
Constructs the TensorBoard WSGI app and instantiates the server.
def _make_server(self): """Constructs the TensorBoard WSGI app and instantiates the server.""" app = application.standard_tensorboard_wsgi(self.flags, self.plugin_loaders, self.assets_zip_provider) return self.se...
Returns a wildcard address for the port in question. This will attempt to follow the best practice of calling getaddrinfo() with a null host and AI_PASSIVE to request a server-side socket wildcard address. If that succeeds, this returns the first IPv6 address found, or if none, then returns the first I...
def _get_wildcard_address(self, port): """Returns a wildcard address for the port in question. This will attempt to follow the best practice of calling getaddrinfo() with a null host and AI_PASSIVE to request a server-side socket wildcard address. If that succeeds, this returns the first IPv6 address f...
Override to enable IPV4 mapping for IPV6 sockets when desired. The main use case for this is so that when no host is specified, TensorBoard can listen on all interfaces for both IPv4 and IPv6 connections, rather than having to choose v4 or v6 and hope the browser didn't choose the other one.
def server_bind(self): """Override to enable IPV4 mapping for IPV6 sockets when desired. The main use case for this is so that when no host is specified, TensorBoard can listen on all interfaces for both IPv4 and IPv6 connections, rather than having to choose v4 or v6 and hope the browser didn't choose...
Override to get rid of noisy EPIPE errors.
def handle_error(self, request, client_address): """Override to get rid of noisy EPIPE errors.""" del request # unused # Kludge to override a SocketServer.py method so we can get rid of noisy # EPIPE errors. They're kind of a red herring as far as errors go. For # example, `curl -N http://localhost...
Iterator over all catapult trace events, as python values.
def _events(self): """Iterator over all catapult trace events, as python values.""" for did, device in sorted(six.iteritems(self._proto.devices)): if device.name: yield dict( ph=_TYPE_METADATA, pid=did, name='process_name', args=dict(name=device.name...
Converts a TraceEvent proto into a catapult trace event python value.
def _event(self, event): """Converts a TraceEvent proto into a catapult trace event python value.""" result = dict( pid=event.device_id, tid=event.resource_id, name=event.name, ts=event.timestamp_ps / 1000000.0) if event.duration_ps: result['ph'] = _TYPE_COMPLETE ...
Create a legacy scalar summary op. Arguments: name: A unique name for the generated summary node. data: A real numeric rank-0 `Tensor`. Must have `dtype` castable to `float32`. display_name: Optional name for this summary in TensorBoard, as a constant `str`. Defaults to `name`. descriptio...
def op(name, data, display_name=None, description=None, collections=None): """Create a legacy scalar summary op. Arguments: name: A unique name for the generated summary node. data: A real numeric rank-0 `Tensor`. Must have `dtype` castable to `float32`. display_name: ...
Create a legacy scalar summary protobuf. Arguments: name: A unique name for the generated summary, including any desired name scopes. data: A rank-0 `np.array` or array-like form (so raw `int`s and `float`s are fine, too). display_name: Optional name for this summary in TensorBoard, as a ...
def pb(name, data, display_name=None, description=None): """Create a legacy scalar summary protobuf. Arguments: name: A unique name for the generated summary, including any desired name scopes. data: A rank-0 `np.array` or array-like form (so raw `int`s and `float`s are fine, too). display_...
Creates temp symlink tree, runs program, and copies back outputs. Args: inputs: List of fake paths to real paths, which are used for symlink tree. program: List containing real path of program and its arguments. The execroot directory will be appended as the last argument. outputs: List of fake o...
def run(inputs, program, outputs): """Creates temp symlink tree, runs program, and copies back outputs. Args: inputs: List of fake paths to real paths, which are used for symlink tree. program: List containing real path of program and its arguments. The execroot directory will be appended as the la...
Invokes run function using a JSON file config. Args: args: CLI args, which can be a JSON file containing an object whose attributes are the parameters to the run function. If multiple JSON files are passed, their contents are concatenated. Returns: 0 if succeeded or nonzero if failed. Rai...
def main(args): """Invokes run function using a JSON file config. Args: args: CLI args, which can be a JSON file containing an object whose attributes are the parameters to the run function. If multiple JSON files are passed, their contents are concatenated. Returns: 0 if succeeded or non...
Initializes the TensorBoard sqlite schema using the given connection. Args: connection: A sqlite DB connection.
def initialize_schema(connection): """Initializes the TensorBoard sqlite schema using the given connection. Args: connection: A sqlite DB connection. """ cursor = connection.cursor() cursor.execute("PRAGMA application_id={}".format(_TENSORBOARD_APPLICATION_ID)) cursor.execute("PRAGMA user_version={}".f...
Returns a freshly created DB-wide unique ID.
def _create_id(self): """Returns a freshly created DB-wide unique ID.""" cursor = self._db.cursor() cursor.execute('INSERT INTO Ids DEFAULT VALUES') return cursor.lastrowid
Returns the ID for the current user, creating the row if needed.
def _maybe_init_user(self): """Returns the ID for the current user, creating the row if needed.""" user_name = os.environ.get('USER', '') or os.environ.get('USERNAME', '') cursor = self._db.cursor() cursor.execute('SELECT user_id FROM Users WHERE user_name = ?', (user_name,)) row ...
Returns the ID for the given experiment, creating the row if needed. Args: experiment_name: name of experiment.
def _maybe_init_experiment(self, experiment_name): """Returns the ID for the given experiment, creating the row if needed. Args: experiment_name: name of experiment. """ user_id = self._maybe_init_user() cursor = self._db.cursor() cursor.execute( """ SELECT experiment_id F...