INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the summary metadata for the given tag on the given run.
def SummaryMetadata(self, run, tag): """Return the summary metadata for the given tag on the given run. Args: run: A string name of the run for which summary metadata is to be retrieved. tag: A string name of the tag whose summary metadata is to be retrieved. Raises: KeyE...
Return all the run names in the EventMultiplexer.
def Runs(self): """Return all the run names in the `EventMultiplexer`. Returns: ``` {runName: { scalarValues: [tagA, tagB, tagC], graph: true, meta_graph: true}} ``` """ with self._accumulators_mutex: # To avoid nested locks, we construct a copy of the run-accumula...
Write a text summary.
def text(name, data, step=None, description=None): """Write a text 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 UTF-8 string tensor value. step: Explicit `int64`-castable monotonic step value ...
Create a text tf. Summary protobuf.
def text_pb(tag, data, description=None): """Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type bytes), a Unicode string, or a numpy data array of those types. description: Optional long-form description for this summary, as a `str`. ...
Initializes flags and calls main ().
def run_main(): """Initializes flags and calls main().""" program.setup_environment() if getattr(tf, '__version__', 'stub') == 'stub': print("TensorFlow installation not found - running with reduced feature set.", file=sys.stderr) tensorboard = program.TensorBoard(default.get_plugins(), ...
Create a summary_pb2. SummaryMetadata proto for image plugin data.
def create_summary_metadata(display_name, description): """Create a `summary_pb2.SummaryMetadata` proto for image plugin data. Returns: A `summary_pb2.SummaryMetadata` protobuf object. """ content = plugin_data_pb2.ImagePluginData(version=PROTO_VERSION) metadata = summary_pb2.SummaryMetadata( displ...
Create a legacy audio summary op for use in a TensorFlow graph.
def op(name, audio, sample_rate, labels=None, max_outputs=3, encoding=None, display_name=None, description=None, collections=None): """Create a legacy audio summary op for use in a TensorFlow graph. Arguments: name: A unique name for the generated summary...
Create a legacy audio summary protobuf.
def pb(name, audio, sample_rate, labels=None, max_outputs=3, encoding=None, display_name=None, description=None): """Create a legacy audio summary protobuf. This behaves as if you were to create an `op` with the same arguments (wrapped with constant tensors where ...
Create a PR curve summary op for a single binary classifier.
def op( name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None, collections=None): """Create a PR curve summary op for a single binary classifier. Computes true/false positive/negative values for the given `predictions` against the ground...
Create a PR curves summary protobuf.
def pb(name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None): """Create a PR curves summary protobuf. Arguments: name: A name for the generated node. Will also serve as a series name in TensorBoard. labels: The g...
Computes a precision - recall curve summary across batches of data.
def streaming_op(name, labels, predictions, num_thresholds=None, weights=None, metrics_collections=None, updates_collections=None, display_name=None, description=None): """Computes a...
Create an op that collects data for visualizing PR curves.
def raw_data_op( name, true_positive_counts, false_positive_counts, true_negative_counts, false_negative_counts, precision, recall, num_thresholds=None, display_name=None, description=None, collections=None): """Create an op that collects data for visualizing PR curves. ...
Create a PR curves summary protobuf from raw data values.
def raw_data_pb( name, true_positive_counts, false_positive_counts, true_negative_counts, false_negative_counts, precision, recall, num_thresholds=None, display_name=None, description=None): """Create a PR curves summary protobuf from raw data values. Args: name: A tag a...
A private helper method for generating a tensor summary.
def _create_tensor_summary( name, true_positive_counts, false_positive_counts, true_negative_counts, false_negative_counts, precision, recall, num_thresholds=None, display_name=None, description=None, collections=None): """A private helper method for generating a tensor sum...
Executes the request.
def run(self): """Executes the request. Returns: An array of tuples representing the metric evaluations--each of the form (<wall time in secs>, <training step>, <metric value>). """ run, tag = metrics.run_tag_from_session_and_metric( self._request.session_name, self._request.metri...
This plugin is active iff any run has at least one histograms tag.
def is_active(self): """This plugin is active iff any run has at least one histograms tag.""" if self._db_connection_provider: # The plugin is active if one relevant tag can be found in the database. db = self._db_connection_provider() cursor = db.execute(''' SELECT 1 ...
Result of the form ( body mime_type ) or ValueError.
def histograms_impl(self, tag, run, downsample_to=None): """Result of the form `(body, mime_type)`, or `ValueError`. At most `downsample_to` events will be returned. If this value is `None`, then no downsampling will be performed. """ if self._db_connection_provider: # Serve data from the dat...
Obtains values for histogram data given blob and dtype enum. Args: data_blob: The blob obtained from the database. dtype_enum: The enum representing the dtype. shape_string: A comma - separated string of numbers denoting shape. Returns: The histogram values as a list served to the frontend.
def _get_values(self, data_blob, dtype_enum, shape_string): """Obtains values for histogram data given blob and dtype enum. Args: data_blob: The blob obtained from the database. dtype_enum: The enum representing the dtype. shape_string: A comma-separated string of numbers denoting shape. R...
Given a tag and single run return array of histogram values.
def histograms_route(self, request): """Given a tag and single run, return array of histogram values.""" tag = request.args.get('tag') run = request.args.get('run') try: (body, mime_type) = self.histograms_impl( tag, run, downsample_to=self.SAMPLE_SIZE) code = 200 except ValueE...
Initialize the graph and session if this has not yet been done.
def _lazily_initialize(self): """Initialize the graph and session, if this has not yet been done.""" # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf with self._initialization_lock: if self._session: return graph = tf.Graph() ...
Tries to get the scalars plugin.
def _get_scalars_plugin(self): """Tries to get the scalars plugin. Returns: The scalars plugin. Or None if it is not yet registered. """ if scalars_metadata.PLUGIN_NAME in self._plugin_name_to_instance: # The plugin is registered. return self._plugin_name_to_instance[scalars_metadata....
This plugin is active if 2 conditions hold.
def is_active(self): """This plugin is active if 2 conditions hold. 1. The scalars plugin is registered and active. 2. There is a custom layout for the dashboard. Returns: A boolean. Whether the plugin is active. """ if not self._multiplexer: return False scalars_plugin_instance = s...
Provides a response for downloading scalars data for a data series.
def download_data_impl(self, run, tag, response_format): """Provides a response for downloading scalars data for a data series. Args: run: The run. tag: The specific tag. response_format: A string. One of the values of the OutputFormat enum of the scalar plugin. Raises: Val...
Given a tag regex and single run return ScalarEvents.
def scalars_route(self, request): """Given a tag regex and single run, return ScalarEvents. This route takes 2 GET params: run: A run string to find tags for. tag: A string that is a regex used to find matching tags. The response is a JSON object: { // Whether the regular expression is va...
Given a tag regex and single run return ScalarEvents.
def scalars_impl(self, run, tag_regex_string): """Given a tag regex and single run, return ScalarEvents. Args: run: A run string. tag_regex_string: A regular expression that captures portions of tags. Raises: ValueError: if the scalars plugin is not registered. Returns: A dict...
r Fetches the custom layout specified by the config file in the logdir.
def layout_route(self, request): r"""Fetches the custom layout specified by the config file in the logdir. If more than 1 run contains a layout, this method merges the layouts by merging charts within individual categories. If 2 categories with the same name are found, the charts within are merged. The...
Given an iterable of string contents make a table row.
def make_table_row(contents, tag='td'): """Given an iterable of string contents, make a table row. Args: contents: An iterable yielding strings. tag: The tag to place contents in. Defaults to 'td', you might want 'th'. Returns: A string containing the content strings, organized into a table row. ...
Given a numpy ndarray of strings concatenate them into a html table.
def make_table(contents, headers=None): """Given a numpy ndarray of strings, concatenate them into a html table. Args: contents: A np.ndarray of strings. May be 1d or 2d. In the 1d case, the table is laid out vertically (i.e. row-major). headers: A np.ndarray or list of string header names for the ta...
Given a np. npdarray with nDims > 2 reduce it to 2d.
def reduce_to_2d(arr): """Given a np.npdarray with nDims > 2, reduce it to 2d. It does this by selecting the zeroth coordinate for every dimension greater than two. Args: arr: a numpy ndarray of dimension at least 2. Returns: A two-dimensional subarray from the input array. Raises: ValueErro...
Take a numpy. ndarray containing strings and convert it into html.
def text_array_to_html(text_arr): """Take a numpy.ndarray containing strings, and convert it into html. If the ndarray contains a single scalar string, that string is converted to html via our sanitized markdown parser. If it contains an array of strings, the strings are individually converted to html and then...
Convert a TensorEvent into a JSON - compatible response.
def process_string_tensor_event(event): """Convert a TensorEvent into a JSON-compatible response.""" string_arr = tensor_util.make_ndarray(event.tensor_proto) html = text_array_to_html(string_arr) return { 'wall_time': event.wall_time, 'step': event.step, 'text': html, }
Determines whether this plugin is active.
def is_active(self): """Determines whether this plugin is active. This plugin is only active if TensorBoard sampled any text summaries. Returns: Whether this plugin is active. """ if not self._multiplexer: return False if self._index_cached is not None: # If we already have ...
Attempts to launch a thread to compute index_impl ().
def _maybe_launch_index_impl_thread(self): """Attempts to launch a thread to compute index_impl(). This may not launch a new thread if one is already running to compute index_impl(); in that case, this function is a no-op. """ # Try to acquire the lock for computing index_impl(), without blocking. ...
Computes index_impl () asynchronously on a separate thread.
def _async_index_impl(self): """Computes index_impl() asynchronously on a separate thread.""" start = time.time() logger.info('TextPlugin computing index_impl() in a new thread') self._index_cached = self.index_impl() self._index_impl_thread = None self._index_impl_lock.release() elapsed = t...
Create a summary_pb2. SummaryMetadata proto for pr_curves plugin data.
def create_summary_metadata(display_name, description, num_thresholds): """Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data. Arguments: display_name: The display name used in TensorBoard. description: The description to show in TensorBoard. num_thresholds: The number of thresholds...
Parse summary metadata to a Python object.
def parse_plugin_metadata(content): """Parse summary metadata to a Python object. Arguments: content: The `content` field of a `SummaryMetadata` proto corresponding to the pr_curves plugin. Returns: A `PrCurvesPlugin` protobuf object. """ if not isinstance(content, bytes): raise TypeError(...
Return a field to Observations dict for the event generator.
def get_field_to_observations_map(generator, query_for_tag=''): """Return a field to `Observations` dict for the event generator. Args: generator: A generator over event protos. query_for_tag: A string that if specified, only create observations for events with this tag name. Returns: A dict m...
Returns a dictionary of tags that a user could query over.
def get_unique_tags(field_to_obs): """Returns a dictionary of tags that a user could query over. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict that maps keys in `TAG_FIELDS` to a list of string tags present in the event files. If the dict does not have any ob...
Prints a shallow dict to console.
def print_dict(d, show_missing=True): """Prints a shallow dict to console. Args: d: Dict to print. show_missing: Whether to show keys with empty values. """ for k, v in sorted(d.items()): if (not v) and show_missing: # No instances of the key, so print missing symbol. print('{} -'.forma...
Transform the field - to - obs mapping into a printable dictionary.
def get_dict_to_print(field_to_obs): """Transform the field-to-obs mapping into a printable dictionary. Args: field_to_obs: Dict that maps string field to `Observation` list. Returns: A dict with the keys and values to print to console. """ def compressed_steps(steps): return {'num_steps': len(...
Returns elements that break the monotonically non - decreasing trend.
def get_out_of_order(list_of_numbers): """Returns elements that break the monotonically non-decreasing trend. This is used to find instances of global step values that are "out-of-order", which may trigger TensorBoard event discarding logic. Args: list_of_numbers: A list of numbers. Returns: A list...
Returns a list of event generators for subdirectories with event files.
def generators_from_logdir(logdir): """Returns a list of event generators for subdirectories with event files. The number of generators returned should equal the number of directories within logdir that contain event files. If only logdir contains event files, returns a list of length one. Args: logdir:...
Returns a list of InspectionUnit objects given either logdir or event_file.
def get_inspection_units(logdir='', event_file='', tag=''): """Returns a list of InspectionUnit objects given either logdir or event_file. If logdir is given, the number of InspectionUnits should equal the number of directories or subdirectories that contain event files. If event_file is given, the number of ...
Main function for inspector that prints out a digest of event files.
def inspect(logdir='', event_file='', tag=''): """Main function for inspector that prints out a digest of event files. Args: logdir: A log directory that contains event files. event_file: Or, a particular event file path. tag: An optional tag name to query for. Raises: ValueError: If neither log...
Adds DebuggerPlugin CLI flags to parser.
def define_flags(self, parser): """Adds DebuggerPlugin CLI flags to parser.""" group = parser.add_argument_group('debugger plugin') group.add_argument( '--debugger_data_server_grpc_port', metavar='PORT', type=int, default=-1, help='''\ The port at which the non-intera...
Returns the debugger plugin if possible.
def load(self, context): """Returns the debugger plugin, if possible. Args: context: The TBContext flags including `add_arguments`. Returns: A DebuggerPlugin instance or None if it couldn't be loaded. """ if not (context.flags.debugger_data_server_grpc_port > 0 or context.f...
Returns a summary metadata for the HParams plugin.
def create_summary_metadata(hparams_plugin_data_pb): """Returns a summary metadata for the HParams plugin. Returns a summary_pb2.SummaryMetadata holding a copy of the given HParamsPluginData message in its plugin_data.content field. Sets the version field of the hparams_plugin_data_pb copy to PLUGIN_DATA_VER...
Returns a data oneof s field from plugin_data. content.
def _parse_plugin_data_as(content, data_oneof_field): """Returns a data oneof's field from plugin_data.content. Raises HParamsError if the content doesn't have 'data_oneof_field' set or this file is incompatible with the version of the metadata stored. Args: content: The SummaryMetadata.plugin_data.conten...
Writes an event proto to disk.
def write_event(self, event): """Writes an event proto to disk. This method is threadsafe with respect to invocations of itself. Args: event: The event proto. Raises: IOError: If writing the event proto to disk fails. """ self._lock.acquire() try: self._events_writer.Wri...
Disposes of this events writer manager making it no longer usable.
def dispose(self): """Disposes of this events writer manager, making it no longer usable. Call this method when this object is done being used in order to clean up resources and handlers. This method should ever only be called once. """ self._lock.acquire() self._events_writer.Close() self....
Creates a new events writer.
def _create_events_writer(self, directory): """Creates a new events writer. Args: directory: The directory in which to write files containing events. Returns: A new events writer, which corresponds to a new events file. """ total_size = 0 events_files = self._fetch_events_files_on_...
Obtains the names of debugger - related events files within the directory.
def _fetch_events_files_on_disk(self): """Obtains the names of debugger-related events files within the directory. Returns: The names of the debugger-related events files written to disk. The names are sorted in increasing events file index. """ all_files = tf.io.gfile.listdir(self._events_...
Re - export all symbols from the original tf. summary.
def reexport_tf_summary(): """Re-export all symbols from the original tf.summary. This function finds the original tf.summary V2 API and re-exports all the symbols from it within this module as well, so that when this module is patched into the TF API namespace as the new tf.summary, the effect is an overlay...
Encode image to PNG on thread_count threads in parallel.
def bench(image, thread_count): """Encode `image` to PNG on `thread_count` threads in parallel. Returns: A `float` representing number of seconds that it takes all threads to finish encoding `image`. """ threads = [threading.Thread(target=lambda: encoder.encode_png(image)) for _ in xrange(...
Generate a square RGB test image of the given side length.
def _image_of_size(image_size): """Generate a square RGB test image of the given side length.""" return np.random.uniform(0, 256, [image_size, image_size, 3]).astype(np.uint8)
Format a line of a table.
def _format_line(headers, fields): """Format a line of a table. Arguments: headers: A list of strings that are used as the table headers. fields: A list of the same length as `headers` where `fields[i]` is the entry for `headers[i]` in this row. Elements can be of arbitrary types. Pass `headers...
Extract all nodes with gated - gRPC debug ops attached.
def get_gated_grpc_tensors(self, matching_debug_op=None): """Extract all nodes with gated-gRPC debug ops attached. Uses cached values if available. This method is thread-safe. Args: graph_def: A tf.GraphDef proto. matching_debug_op: Return tensors and nodes with only matching the s...
Expand the base name if there are node names nested under the node.
def maybe_base_expanded_node_name(self, node_name): """Expand the base name if there are node names nested under the node. For example, if there are two nodes in the graph, "a" and "a/read", then calling this function on "a" will give "a/(a)", a form that points at a leaf node in the nested TensorBoard...
Load runs from a directory ; recursively walks subdirectories.
def AddRunsFromDirectory(self, path, name=None): """Load runs from a directory; recursively walks subdirectories. If path doesn't exist, no-op. This ensures that it is safe to call `AddRunsFromDirectory` multiple times, even before the directory is made. Args: path: A string path to a director...
Load events from every detected run.
def Reload(self): """Load events from every detected run.""" logger.info('Beginning DbImportMultiplexer.Reload()') # Defer event sink creation until needed; this ensures it will only exist in # the thread that calls Reload(), since DB connections must be thread-local. if not self._event_sink: ...
Returns a batched event iterator over the run directory event files.
def load_batches(self): """Returns a batched event iterator over the run directory event files.""" event_iterator = self._directory_watcher.Load() while True: events = [] event_bytes = 0 start = time.time() for event_proto in event_iterator: events.append(event_proto) ...
Processes a single tf. Event and records it in tagged_data.
def _process_event(self, event, tagged_data): """Processes a single tf.Event and records it in tagged_data.""" event_type = event.WhichOneof('what') # Handle the most common case first. if event_type == 'summary': for value in event.summary.value: value = data_compat.migrate_value(value) ...
Create a TensorFlow op to group data into histogram buckets.
def _buckets(data, bucket_count=None): """Create a TensorFlow op to group data into histogram buckets. Arguments: data: A `Tensor` of any shape. Must be castable to `float64`. bucket_count: Optional positive `int` or scalar `int32` `Tensor`. Returns: A `Tensor` of shape `[k, 3]` and type `float64`. T...
Create a legacy histogram summary op.
def op(name, data, bucket_count=None, display_name=None, description=None, collections=None): """Create a legacy histogram summary op. Arguments: name: A unique name for the generated summary node. data: A `Tensor` of any shape. Must be castable to `float64`. bucket_c...
Create a legacy histogram summary protobuf.
def pb(name, data, bucket_count=None, display_name=None, description=None): """Create a legacy histogram summary protobuf. Arguments: name: A unique name for the generated summary, including any desired name scopes. data: A `np.array` or array-like form of any shape. Must have type castable to ...
Add a tensor the watch store.
def add(self, value): """Add a tensor the watch store.""" if self._disposed: raise ValueError( 'Cannot add value: this _WatchStore instance is already disposed') self._data.append(value) if hasattr(value, 'nbytes'): self._in_mem_bytes += value.nbytes self._ensure_bytes_limits...
Get number of values in memory.
def num_in_memory(self): """Get number of values in memory.""" n = len(self._data) - 1 while n >= 0: if isinstance(self._data[n], _TensorValueDiscarded): break n -= 1 return len(self._data) - 1 - n
Get the number of values discarded due to exceeding both limits.
def num_discarded(self): """Get the number of values discarded due to exceeding both limits.""" if not self._data: return 0 n = 0 while n < len(self._data): if not isinstance(self._data[n], _TensorValueDiscarded): break n += 1 return n
Query the values at given time indices.
def query(self, time_indices): """Query the values at given time indices. Args: time_indices: 0-based time indices to query, as a `list` of `int`. Returns: Values as a list of `numpy.ndarray` (for time indices in memory) or `None` (for time indices discarded). """ if self._dispos...
Add a tensor value.
def add(self, watch_key, tensor_value): """Add a tensor value. Args: watch_key: A string representing the debugger tensor watch, e.g., 'Dense_1/BiasAdd:0:DebugIdentity'. tensor_value: The value of the tensor as a numpy.ndarray. """ if watch_key not in self._tensor_data: self._...
Query tensor store for a given watch_key.
def query(self, watch_key, time_indices=None, slicing=None, mapping=None): """Query tensor store for a given watch_key. Args: watch_key: The watch key to query. time_indices: A numpy-style slicing string for time indices. E.g., `-1`, `:-2`, `[...
Start listening on the given gRPC port.
def listen(self, grpc_port): """Start listening on the given gRPC port. This method of an instance of DebuggerPlugin can be invoked at most once. This method is not thread safe. Args: grpc_port: port number to listen at. Raises: ValueError: If this instance is already listening at a g...
Determines whether this plugin is active.
def is_active(self): """Determines whether this plugin is active. This plugin is active if any health pills information is present for any run. Returns: A boolean. Whether this plugin is active. """ return bool( self._grpc_port is not None and self._event_multiplexer and ...
A ( wrapped ) werkzeug handler for serving health pills.
def _serve_health_pills_handler(self, request): """A (wrapped) werkzeug handler for serving health pills. Accepts POST requests and responds with health pills. The request accepts several POST parameters: node_names: (required string) A JSON-ified list of node names for which the client wo...
Obtains the health pills for a run sampled by the event multiplexer.
def _obtain_sampled_health_pills(self, run, node_names): """Obtains the health pills for a run sampled by the event multiplexer. This is much faster than the alternative path of reading health pills from disk. Args: run: The run to fetch health pills for. node_names: A list of node names f...
Converts an event_accumulator. TensorEvent to a HealthPillEvent.
def _tensor_proto_to_health_pill(self, tensor_event, node_name, device, output_slot): """Converts an event_accumulator.TensorEvent to a HealthPillEvent. Args: tensor_event: The event_accumulator.TensorEvent to convert. node_name: The name of the node (without the ...
Reads disk to obtain the health pills for a run at a specific step.
def _obtain_health_pills_at_step(self, events_directory, node_names, step): """Reads disk to obtain the health pills for a run at a specific step. This could be much slower than the alternative path of just returning all health pills sampled by the event multiplexer. It could take tens of minutes to co...
Creates health pills out of data in an event.
def _process_health_pill_event(self, node_name_set, mapping, target_step, file_path): """Creates health pills out of data in an event. Creates health pills out of the event and adds them to the mapping. Args: node_name_set: A set of node names that are relevant. ...
Creates a HealthPillEvent containing various properties of a health pill.
def _process_health_pill_value(self, wall_time, step, device_name, output_slot, node_name, tensor_proto, ...
A ( wrapped ) werkzeug handler for serving numerics alert report.
def _serve_numerics_alert_report_handler(self, request): """A (wrapped) werkzeug handler for serving numerics alert report. Accepts GET requests and responds with an array of JSON-ified NumericsAlertReportRow. Each JSON-ified NumericsAlertReportRow object has the following format: { 'devic...
Convert a TensorBoardInfo to string form to be stored on disk.
def _info_to_string(info): """Convert a `TensorBoardInfo` to string form to be stored on disk. The format returned by this function is opaque and should only be interpreted by `_info_from_string`. Args: info: A valid `TensorBoardInfo` object. Raises: ValueError: If any field on `info` is not of the...
Parse a TensorBoardInfo object from its string representation.
def _info_from_string(info_string): """Parse a `TensorBoardInfo` object from its string representation. Args: info_string: A string representation of a `TensorBoardInfo`, as produced by a previous call to `_info_to_string`. Returns: A `TensorBoardInfo` value. Raises: ValueError: If the prov...
Compute a TensorBoardInfo. cache_key field.
def cache_key(working_directory, arguments, configure_kwargs): """Compute a `TensorBoardInfo.cache_key` field. The format returned by this function is opaque. Clients may only inspect it by comparing it for equality with other results from this function. Args: working_directory: The directory from which...
Get path to directory in which to store info files.
def _get_info_dir(): """Get path to directory in which to store info files. The directory returned by this function is "owned" by this module. If the contents of the directory are modified other than via the public functions of this module, subsequent behavior is undefined. The directory will be created if ...
Write TensorBoardInfo to the current process s info file.
def write_info_file(tensorboard_info): """Write TensorBoardInfo to the current process's info file. This should be called by `main` once the server is ready. When the server shuts down, `remove_info_file` should be called. Args: tensorboard_info: A valid `TensorBoardInfo` object. Raises: ValueError...
Remove the current process s TensorBoardInfo file if it exists.
def remove_info_file(): """Remove the current process's TensorBoardInfo file, if it exists. If the file does not exist, no action is taken and no error is raised. """ try: os.unlink(_get_info_file_path()) except OSError as e: if e.errno == errno.ENOENT: # The user may have wiped their temporary...
Return TensorBoardInfo values for running TensorBoard processes.
def get_all(): """Return TensorBoardInfo values for running TensorBoard processes. This function may not provide a perfect snapshot of the set of running processes. Its result set may be incomplete if the user has cleaned their /tmp/ directory while TensorBoard processes are running. It may contain extraneou...
Start a new TensorBoard instance or reuse a compatible one.
def start(arguments, timeout=datetime.timedelta(seconds=60)): """Start a new TensorBoard instance, or reuse a compatible one. If the cache key determined by the provided arguments and the current working directory (see `cache_key`) matches the cache key of a running TensorBoard process (see `get_all`), that pr...
Find a running TensorBoard instance compatible with the cache key.
def _find_matching_instance(cache_key): """Find a running TensorBoard instance compatible with the cache key. Returns: A `TensorBoardInfo` object, or `None` if none matches the cache key. """ infos = get_all() candidates = [info for info in infos if info.cache_key == cache_key] for candidate in sorted(...
Read the given file if it exists.
def _maybe_read_file(filename): """Read the given file, if it exists. Args: filename: A path to a file. Returns: A string containing the file contents, or `None` if the file does not exist. """ try: with open(filename) as infile: return infile.read() except IOError as e: if e.err...
Processes raw trace data and returns the UI data.
def process_raw_trace(raw_trace): """Processes raw trace data and returns the UI data.""" trace = trace_events_pb2.Trace() trace.ParseFromString(raw_trace) return ''.join(trace_events_json.TraceEventsJsonStream(trace))
Whether this plugin is active and has any profile data to show.
def is_active(self): """Whether this plugin is active and has any profile data to show. Detecting profile data is expensive, so this process runs asynchronously and the value reported by this method is the cached value and may be stale. Returns: Whether any run has profile data. """ # If...
Helper that maps a frontend run name to a profile run directory.
def _run_dir(self, run): """Helper that maps a frontend run name to a profile "run" directory. The frontend run name consists of the TensorBoard run name (aka the relative path from the logdir root to the directory containing the data) path-joined to the Profile plugin's "run" concept (which is a subdi...
Generator for pairs of run name and a list of tools for that run.
def generate_run_to_tools(self): """Generator for pairs of "run name" and a list of tools for that run. The "run name" here is a "frontend run name" - see _run_dir() for the definition of a "frontend run name" and how it maps to a directory of profile data for a specific profile "run". The profile plug...
Returns available hosts for the run and tool in the log directory.
def host_impl(self, run, tool): """Returns available hosts for the run and tool in the log directory. In the plugin log directory, each directory contains profile data for a single run (identified by the directory name), and files in the run directory contains data for different tools and hosts. The fi...
Retrieves and processes the tool data for a run and a host.
def data_impl(self, request): """Retrieves and processes the tool data for a run and a host. Args: request: XMLHttpRequest Returns: A string that can be served to the frontend tool or None if tool, run or host is invalid. """ run = request.args.get('run') tool = request.arg...
Run a temperature simulation.
def run(logdir, run_name, initial_temperature, ambient_temperature, heat_coefficient): """Run 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...
Run simulations on a reasonable set of parameters.
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 """ for initial_temperature in [270.0, 310.0, 350.0]: for final_temperature in [...
Makes Python object appropriate for JSON serialization.
def Cleanse(obj, encoding='utf-8'): """Makes Python object appropriate for JSON serialization. - Replaces instances of Infinity/-Infinity/NaN with strings. - Turns byte strings into unicode strings. - Turns sets into sorted lists. - Turns tuples into lists. Args: obj: Python data structure. encodi...
Create a legacy text summary op.
def op(name, data, display_name=None, description=None, collections=None): """Create a legacy text summary op. Text data summarized via this plugin will be visible in the Text Dashboard in TensorBoard. The standard TensorBoard Text Dashboard will render markdown in the strings, and ...