Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def parse_plugin_metadata(content): if not isinstance(content, bytes): raise TypeError('Content type must be bytes') result = plugin_data_pb2.PrCurvePluginData.FromString(content) if result.version == 0: return result else: logger.warn( 'Unknow...
[ "Parse summary metadata to a Python object.\n\n Arguments:\n content: The `content` field of a `SummaryMetadata` proto\n corresponding to the pr_curves plugin.\n\n Returns:\n A `PrCurvesPlugin` protobuf object.\n " ]
Please provide a description of the function:def get_field_to_observations_map(generator, query_for_tag=''): def increment(stat, event, tag=''): assert stat in TRACKED_FIELDS field_to_obs[stat].append(Observation(step=event.step, wall_time=event.wall_time, ...
[ "Return a field to `Observations` dict for the event generator.\n\n Args:\n generator: A generator over event protos.\n query_for_tag: A string that if specified, only create observations for\n events with this tag name.\n\n Returns:\n A dict mapping keys in `TRACKED_FIELDS` to an `Observation` list...
Please provide a description of the function:def get_unique_tags(field_to_obs): return {field: sorted(set([x.get('tag', '') for x in observations])) for field, observations in field_to_obs.items() if field in TAG_FIELDS}
[ "Returns a dictionary of tags that a user could query over.\n\n Args:\n field_to_obs: Dict that maps string field to `Observation` list.\n\n Returns:\n A dict that maps keys in `TAG_FIELDS` to a list of string tags present in\n the event files. If the dict does not have any observations of the type,\n ...
Please provide a description of the function:def print_dict(d, show_missing=True): for k, v in sorted(d.items()): if (not v) and show_missing: # No instances of the key, so print missing symbol. print('{} -'.format(k)) elif isinstance(v, list): # Value is a list, so print each item of the...
[ "Prints a shallow dict to console.\n\n Args:\n d: Dict to print.\n show_missing: Whether to show keys with empty values.\n " ]
Please provide a description of the function:def get_dict_to_print(field_to_obs): def compressed_steps(steps): return {'num_steps': len(set(steps)), 'min_step': min(steps), 'max_step': max(steps), 'last_step': steps[-1], 'first_step': steps[0], 'outo...
[ "Transform the field-to-obs mapping into a printable dictionary.\n\n Args:\n field_to_obs: Dict that maps string field to `Observation` list.\n\n Returns:\n A dict with the keys and values to print to console.\n " ]
Please provide a description of the function:def get_out_of_order(list_of_numbers): # TODO: Consider changing this to only check for out-of-order # steps within a particular tag. result = [] # pylint: disable=consider-using-enumerate for i in range(len(list_of_numbers)): if i == 0: continue i...
[ "Returns elements that break the monotonically non-decreasing trend.\n\n This is used to find instances of global step values that are \"out-of-order\",\n which may trigger TensorBoard event discarding logic.\n\n Args:\n list_of_numbers: A list of numbers.\n\n Returns:\n A list of tuples in which each tup...
Please provide a description of the function:def generators_from_logdir(logdir): subdirs = io_wrapper.GetLogdirSubdirectories(logdir) generators = [ itertools.chain(*[ generator_from_event_file(os.path.join(subdir, f)) for f in tf.io.gfile.listdir(subdir) if io_wrapper.IsTenso...
[ "Returns a list of event generators for subdirectories with event files.\n\n The number of generators returned should equal the number of directories\n within logdir that contain event files. If only logdir contains event files,\n returns a list of length one.\n\n Args:\n logdir: A log directory that contain...
Please provide a description of the function:def get_inspection_units(logdir='', event_file='', tag=''): if logdir: subdirs = io_wrapper.GetLogdirSubdirectories(logdir) inspection_units = [] for subdir in subdirs: generator = itertools.chain(*[ generator_from_event_file(os.path.join(sub...
[ "Returns a list of InspectionUnit objects given either logdir or event_file.\n\n If logdir is given, the number of InspectionUnits should equal the\n number of directories or subdirectories that contain event files.\n\n If event_file is given, the number of InspectionUnits should be 1.\n\n Args:\n logdir: A ...
Please provide a description of the function:def inspect(logdir='', event_file='', tag=''): print(PRINT_SEPARATOR + 'Processing event files... (this can take a few minutes)\n' + PRINT_SEPARATOR) inspection_units = get_inspection_units(logdir, event_file, tag) for unit in inspection_units: ...
[ "Main function for inspector that prints out a digest of event files.\n\n Args:\n logdir: A log directory that contains event files.\n event_file: Or, a particular event file path.\n tag: An optional tag name to query for.\n\n Raises:\n ValueError: If neither logdir and event_file are given, or both a...
Please provide a description of the function:def define_flags(self, 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-interac...
[ "Adds DebuggerPlugin CLI flags to parser." ]
Please provide a description of the function:def load(self, context): if not (context.flags.debugger_data_server_grpc_port > 0 or context.flags.debugger_port > 0): return None flags = context.flags try: # pylint: disable=g-import-not-at-top,unused-import import tensorflow ...
[ "Returns the debugger plugin, if possible.\n\n Args:\n context: The TBContext flags including `add_arguments`.\n\n Returns:\n A DebuggerPlugin instance or None if it couldn't be loaded.\n " ]
Please provide a description of the function:def create_summary_metadata(hparams_plugin_data_pb): if not isinstance(hparams_plugin_data_pb, plugin_data_pb2.HParamsPluginData): raise TypeError('Needed an instance of plugin_data_pb2.HParamsPluginData.' ' Got: %s' % type(hparams_plugin_data_pb...
[ "Returns a summary metadata for the HParams plugin.\n\n Returns a summary_pb2.SummaryMetadata holding a copy of the given\n HParamsPluginData message in its plugin_data.content field.\n Sets the version field of the hparams_plugin_data_pb copy to\n PLUGIN_DATA_VERSION.\n\n Args:\n hparams_plugin_data_pb: th...
Please provide a description of the function:def _parse_plugin_data_as(content, data_oneof_field): plugin_data = plugin_data_pb2.HParamsPluginData.FromString(content) if plugin_data.version != PLUGIN_DATA_VERSION: raise error.HParamsError( 'Only supports plugin_data version: %s; found: %s in: %s' % ...
[ "Returns a data oneof's field from plugin_data.content.\n\n Raises HParamsError if the content doesn't have 'data_oneof_field' set or\n this file is incompatible with the version of the metadata stored.\n\n Args:\n content: The SummaryMetadata.plugin_data.content to use.\n data_oneof_field: string. The nam...
Please provide a description of the function:def write_event(self, event): self._lock.acquire() try: self._events_writer.WriteEvent(event) self._event_count += 1 if self._always_flush: # We flush on every event within the integration test. self._events_writer.Flush() ...
[ "Writes an event proto to disk.\n\n This method is threadsafe with respect to invocations of itself.\n\n Args:\n event: The event proto.\n\n Raises:\n IOError: If writing the event proto to disk fails.\n " ]
Please provide a description of the function:def dispose(self): self._lock.acquire() self._events_writer.Close() self._events_writer = None self._lock.release()
[ "Disposes of this events writer manager, making it no longer usable.\n\n Call this method when this object is done being used in order to clean up\n resources and handlers. This method should ever only be called once.\n " ]
Please provide a description of the function:def _create_events_writer(self, directory): total_size = 0 events_files = self._fetch_events_files_on_disk() for file_name in events_files: file_path = os.path.join(self._events_directory, file_name) total_size += tf.io.gfile.stat(file_path).leng...
[ "Creates a new events writer.\n\n Args:\n directory: The directory in which to write files containing events.\n\n Returns:\n A new events writer, which corresponds to a new events file.\n " ]
Please provide a description of the function:def _fetch_events_files_on_disk(self): all_files = tf.io.gfile.listdir(self._events_directory) relevant_files = [ file_name for file_name in all_files if _DEBUGGER_EVENTS_FILE_NAME_REGEX.match(file_name) ] return sorted(relevant_files, ke...
[ "Obtains the names of debugger-related events files within the directory.\n\n Returns:\n The names of the debugger-related events files written to disk. The names\n are sorted in increasing events file index.\n " ]
Please provide a description of the function:def reexport_tf_summary(): import sys # pylint: disable=g-import-not-at-top # API packages to check for the original V2 summary API, in preference order # to avoid going "under the hood" to the _api packages unless necessary. packages = [ 'tensorflow', ...
[ "Re-export all symbols from the original tf.summary.\n\n This function finds the original tf.summary V2 API and re-exports all the\n symbols from it within this module as well, so that when this module is\n patched into the TF API namespace as the new tf.summary, the effect is an\n overlay that just adds Tensor...
Please provide a description of the function:def bench(image, thread_count): threads = [threading.Thread(target=lambda: encoder.encode_png(image)) for _ in xrange(thread_count)] start_time = datetime.datetime.now() for thread in threads: thread.start() for thread in threads: thread.join(...
[ "Encode `image` to PNG on `thread_count` threads in parallel.\n\n Returns:\n A `float` representing number of seconds that it takes all threads\n to finish encoding `image`.\n " ]
Please provide a description of the function:def _image_of_size(image_size): return np.random.uniform(0, 256, [image_size, image_size, 3]).astype(np.uint8)
[ "Generate a square RGB test image of the given side length." ]
Please provide a description of the function:def _format_line(headers, fields): assert len(fields) == len(headers), (fields, headers) fields = ["%2.4f" % field if isinstance(field, float) else str(field) for field in fields] return ' '.join(' ' * max(0, len(header) - len(field)) + field ...
[ "Format a line of a table.\n\n Arguments:\n headers: A list of strings that are used as the table headers.\n fields: A list of the same length as `headers` where `fields[i]` is\n the entry for `headers[i]` in this row. Elements can be of\n arbitrary types. Pass `headers` to print the header row.\n\...
Please provide a description of the function:def get_gated_grpc_tensors(self, matching_debug_op=None): with self._grpc_gated_lock: matching_debug_op = matching_debug_op or 'DebugIdentity' if matching_debug_op not in self._grpc_gated_tensors: # First, construct a map from node name to op typ...
[ "Extract all nodes with gated-gRPC debug ops attached.\n\n Uses cached values if available.\n This method is thread-safe.\n\n Args:\n graph_def: A tf.GraphDef proto.\n matching_debug_op: Return tensors and nodes with only matching the\n specified debug op name (optional). If `None`, will e...
Please provide a description of the function:def maybe_base_expanded_node_name(self, node_name): with self._node_name_lock: # Lazily populate the map from original node name to base-expanded ones. if self._maybe_base_expanded_node_names is None: self._maybe_base_expanded_node_names = dict()...
[ "Expand the base name if there are node names nested under the node.\n\n For example, if there are two nodes in the graph, \"a\" and \"a/read\", then\n calling this function on \"a\" will give \"a/(a)\", a form that points at\n a leaf node in the nested TensorBoard graph. Calling this function on\n \"a/...
Please provide a description of the function:def AddRunsFromDirectory(self, path, name=None): logger.info('Starting AddRunsFromDirectory: %s (as %s)', path, name) for subdir in io_wrapper.GetLogdirSubdirectories(path): logger.info('Processing directory %s', subdir) if subdir not in self._run_lo...
[ "Load runs from a directory; recursively walks subdirectories.\n\n If path doesn't exist, no-op. This ensures that it is safe to call\n `AddRunsFromDirectory` multiple times, even before the directory is made.\n\n Args:\n path: A string path to a directory to load runs from.\n name: Optional, s...
Please provide a description of the function:def Reload(self): 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: ...
[ "Load events from every detected run." ]
Please provide a description of the function:def load_batches(self): 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) event_bytes += len(event_pro...
[ "Returns a batched event iterator over the run directory event files." ]
Please provide a description of the function:def _process_event(self, event, 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) tag, metadat...
[ "Processes a single tf.Event and records it in tagged_data." ]
Please provide a description of the function:def _buckets(data, bucket_count=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf if bucket_count is None: bucket_count = summary_v2.DEFAULT_BUCKET_COUNT with tf.name_scope('buckets', values=[data,...
[ "Create a TensorFlow op to group data into histogram buckets.\n\n Arguments:\n data: A `Tensor` of any shape. Must be castable to `float64`.\n bucket_count: Optional positive `int` or scalar `int32` `Tensor`.\n Returns:\n A `Tensor` of shape `[k, 3]` and type `float64`. The `i`th row is\n a triple `[l...
Please provide a description of the function:def op(name, data, bucket_count=None, display_name=None, description=None, collections=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf if display_name is None: d...
[ "Create a legacy histogram summary op.\n\n Arguments:\n name: A unique name for the generated summary node.\n data: A `Tensor` of any shape. Must be castable to `float64`.\n bucket_count: Optional positive `int`. The output will have this\n many buckets, except in two edge cases. If there is no data,...
Please provide a description of the function:def pb(name, data, bucket_count=None, display_name=None, description=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf if bucket_count is None: bucket_count = summary_v2.DEFAULT_BUCKET_COUNT data ...
[ "Create a legacy histogram summary protobuf.\n\n Arguments:\n name: A unique name for the generated summary, including any desired\n name scopes.\n data: A `np.array` or array-like form of any shape. Must have type\n castable to `float`.\n bucket_count: Optional positive `int`. The output will h...
Please provide a description of the function:def add(self, value): 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_by...
[ "Add a tensor the watch store." ]
Please provide a description of the function:def num_in_memory(self): n = len(self._data) - 1 while n >= 0: if isinstance(self._data[n], _TensorValueDiscarded): break n -= 1 return len(self._data) - 1 - n
[ "Get number of values in memory." ]
Please provide a description of the function:def num_discarded(self): 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
[ "Get the number of values discarded due to exceeding both limits." ]
Please provide a description of the function:def query(self, time_indices): if self._disposed: raise ValueError( 'Cannot query: this _WatchStore instance is already disposed') if not isinstance(time_indices, (tuple, list)): time_indices = [time_indices] output = [] for time_in...
[ "Query the values at given time indices.\n\n Args:\n time_indices: 0-based time indices to query, as a `list` of `int`.\n\n Returns:\n Values as a list of `numpy.ndarray` (for time indices in memory) or\n `None` (for time indices discarded).\n " ]
Please provide a description of the function:def add(self, watch_key, tensor_value): if watch_key not in self._tensor_data: self._tensor_data[watch_key] = _WatchStore( watch_key, mem_bytes_limit=self._watch_mem_bytes_limit) self._tensor_data[watch_key].add(tensor_value)
[ "Add a tensor value.\n\n Args:\n watch_key: A string representing the debugger tensor watch, e.g.,\n 'Dense_1/BiasAdd:0:DebugIdentity'.\n tensor_value: The value of the tensor as a numpy.ndarray.\n " ]
Please provide a description of the function:def query(self, watch_key, time_indices=None, slicing=None, mapping=None): if watch_key not in self._tensor_data: raise KeyError("watch_key not found: %s" % watch_key) if time_indices is None: time_ind...
[ "Query tensor store for a given watch_key.\n\n Args:\n watch_key: The watch key to query.\n time_indices: A numpy-style slicing string for time indices. E.g.,\n `-1`, `:-2`, `[::2]`. If not provided (`None`), will use -1.\n slicing: A numpy-style slicing string for individual time steps.\n ...
Please provide a description of the function:def listen(self, grpc_port): if self._grpc_port: raise ValueError( "This DebuggerPlugin instance is already listening at gRPC port %d" % self._grpc_port) self._grpc_port = grpc_port sys.stderr.write('Creating DebuggerDataServer at ...
[ "Start listening on the given gRPC port.\n\n This method of an instance of DebuggerPlugin can be invoked at most once.\n This method is not thread safe.\n\n Args:\n grpc_port: port number to listen at.\n\n Raises:\n ValueError: If this instance is already listening at a gRPC port.\n " ]
Please provide a description of the function:def is_active(self): return bool( self._grpc_port is not None and self._event_multiplexer and self._event_multiplexer.PluginRunToTagToContent( constants.DEBUGGER_PLUGIN_NAME))
[ "Determines whether this plugin is active.\n\n This plugin is active if any health pills information is present for any\n run.\n\n Returns:\n A boolean. Whether this plugin is active.\n " ]
Please provide a description of the function:def _serve_health_pills_handler(self, request): if request.method != 'POST': return wrappers.Response(response=( '%s requests are forbidden by the debugger plugin.' % request.method), status=405) if _NODE_NAMES_POST_KEY not in request....
[ "A (wrapped) werkzeug handler for serving health pills.\n\n Accepts POST requests and responds with health pills. The request accepts\n several POST parameters:\n\n node_names: (required string) A JSON-ified list of node names for which\n the client would like to request health pills.\n run...
Please provide a description of the function:def _obtain_sampled_health_pills(self, run, node_names): runs_to_tags_to_content = self._event_multiplexer.PluginRunToTagToContent( constants.DEBUGGER_PLUGIN_NAME) if run not in runs_to_tags_to_content: # The run lacks health pills. return {...
[ "Obtains the health pills for a run sampled by the event multiplexer.\n\n This is much faster than the alternative path of reading health pills from\n disk.\n\n Args:\n run: The run to fetch health pills for.\n node_names: A list of node names for which to retrieve health pills.\n\n Returns:\n...
Please provide a description of the function:def _tensor_proto_to_health_pill(self, tensor_event, node_name, device, output_slot): return self._process_health_pill_value( wall_time=tensor_event.wall_time, step=tensor_event.step, device_name=device, ...
[ "Converts an event_accumulator.TensorEvent to a HealthPillEvent.\n\n Args:\n tensor_event: The event_accumulator.TensorEvent to convert.\n node_name: The name of the node (without the output slot).\n device: The device.\n output_slot: The integer output slot this health pill is relevant to.\n...
Please provide a description of the function:def _obtain_health_pills_at_step(self, events_directory, node_names, step): # Obtain all files with debugger-related events. pattern = os.path.join(events_directory, _DEBUGGER_EVENTS_GLOB_PATTERN) file_paths = glob.glob(pattern) if not file_paths: ...
[ "Reads disk to obtain the health pills for a run at a specific step.\n\n This could be much slower than the alternative path of just returning all\n health pills sampled by the event multiplexer. It could take tens of minutes\n to complete this call for large graphs for big step values (in the\n thousan...
Please provide a description of the function:def _process_health_pill_event(self, node_name_set, mapping, target_step, file_path): events_loader = event_file_loader.EventFileLoader(file_path) for event in events_loader.Load(): if not event.HasField('summary'): ...
[ "Creates health pills out of data in an event.\n\n Creates health pills out of the event and adds them to the mapping.\n\n Args:\n node_name_set: A set of node names that are relevant.\n mapping: The mapping from node name to HealthPillEvents.\n This object may be destructively modified.\n ...
Please provide a description of the function:def _process_health_pill_value(self, wall_time, step, device_name, output_slot, node_name, ...
[ "Creates a HealthPillEvent containing various properties of a health pill.\n\n Args:\n wall_time: The wall time in seconds.\n step: The session run step of the event.\n device_name: The name of the node's device.\n output_slot: The numeric output slot.\n node_name: The name of the node (...
Please provide a description of the function:def _serve_numerics_alert_report_handler(self, request): if request.method != 'GET': logger.error( '%s requests are forbidden by the debugger plugin.', request.method) return wrappers.Response(status=405) report = self._debugger_data_serve...
[ "A (wrapped) werkzeug handler for serving numerics alert report.\n\n Accepts GET requests and responds with an array of JSON-ified\n NumericsAlertReportRow.\n\n Each JSON-ified NumericsAlertReportRow object has the following format:\n {\n 'device_name': string,\n 'tensor_name': string,\n ...
Please provide a description of the function:def _info_to_string(info): for key in _TENSORBOARD_INFO_FIELDS: field_type = _TENSORBOARD_INFO_FIELDS[key] if not isinstance(getattr(info, key), field_type.runtime_type): raise ValueError( "expected %r of type %s, but found: %r" % (key,...
[ "Convert a `TensorBoardInfo` to string form to be stored on disk.\n\n The format returned by this function is opaque and should only be\n interpreted by `_info_from_string`.\n\n Args:\n info: A valid `TensorBoardInfo` object.\n\n Raises:\n ValueError: If any field on `info` is not of the correct type.\n\n...
Please provide a description of the function:def _info_from_string(info_string): try: json_value = json.loads(info_string) except ValueError: raise ValueError("invalid JSON: %r" % (info_string,)) if not isinstance(json_value, dict): raise ValueError("not a JSON object: %r" % (json_value,)) if js...
[ "Parse a `TensorBoardInfo` object from its string representation.\n\n Args:\n info_string: A string representation of a `TensorBoardInfo`, as\n produced by a previous call to `_info_to_string`.\n\n Returns:\n A `TensorBoardInfo` value.\n\n Raises:\n ValueError: If the provided string is not valid J...
Please provide a description of the function:def cache_key(working_directory, arguments, configure_kwargs): if not isinstance(arguments, (list, tuple)): raise TypeError( "'arguments' should be a list of arguments, but found: %r " "(use `shlex.split` if given a string)" % (arguments,) ...
[ "Compute a `TensorBoardInfo.cache_key` field.\n\n The format returned by this function is opaque. Clients may only\n inspect it by comparing it for equality with other results from this\n function.\n\n Args:\n working_directory: The directory from which TensorBoard was launched\n and relative to which p...
Please provide a description of the function:def _get_info_dir(): path = os.path.join(tempfile.gettempdir(), ".tensorboard-info") try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST and os.path.isdir(path): pass else: raise else: os.chmod(path, 0o777) return p...
[ "Get path to directory in which to store info files.\n\n The directory returned by this function is \"owned\" by this module. If\n the contents of the directory are modified other than via the public\n functions of this module, subsequent behavior is undefined.\n\n The directory will be created if it does not e...
Please provide a description of the function:def write_info_file(tensorboard_info): payload = "%s\n" % _info_to_string(tensorboard_info) with open(_get_info_file_path(), "w") as outfile: outfile.write(payload)
[ "Write TensorBoardInfo to the current process's info file.\n\n This should be called by `main` once the server is ready. When the\n server shuts down, `remove_info_file` should be called.\n\n Args:\n tensorboard_info: A valid `TensorBoardInfo` object.\n\n Raises:\n ValueError: If any field on `info` is no...
Please provide a description of the function:def remove_info_file(): try: os.unlink(_get_info_file_path()) except OSError as e: if e.errno == errno.ENOENT: # The user may have wiped their temporary directory or something. # Not a problem: we're already in the state that we want to be in. ...
[ "Remove the current process's TensorBoardInfo file, if it exists.\n\n If the file does not exist, no action is taken and no error is raised.\n " ]
Please provide a description of the function:def get_all(): info_dir = _get_info_dir() results = [] for filename in os.listdir(info_dir): filepath = os.path.join(info_dir, filename) try: with open(filepath) as infile: contents = infile.read() except IOError as e: if e.errno == e...
[ "Return TensorBoardInfo values for running TensorBoard processes.\n\n This function may not provide a perfect snapshot of the set of running\n processes. Its result set may be incomplete if the user has cleaned\n their /tmp/ directory while TensorBoard processes are running. It may\n contain extraneous entries ...
Please provide a description of the function:def start(arguments, timeout=datetime.timedelta(seconds=60)): match = _find_matching_instance( cache_key( working_directory=os.getcwd(), arguments=arguments, configure_kwargs={}, ), ) if match: return StartReused(info=ma...
[ "Start a new TensorBoard instance, or reuse a compatible one.\n\n If the cache key determined by the provided arguments and the current\n working directory (see `cache_key`) matches the cache key of a running\n TensorBoard process (see `get_all`), that process will be reused.\n\n Otherwise, a new TensorBoard pr...
Please provide a description of the function:def _find_matching_instance(cache_key): infos = get_all() candidates = [info for info in infos if info.cache_key == cache_key] for candidate in sorted(candidates, key=lambda x: x.port): # TODO(@wchargin): Check here that the provided port is still live. retu...
[ "Find a running TensorBoard instance compatible with the cache key.\n\n Returns:\n A `TensorBoardInfo` object, or `None` if none matches the cache key.\n " ]
Please provide a description of the function:def _maybe_read_file(filename): try: with open(filename) as infile: return infile.read() except IOError as e: if e.errno == errno.ENOENT: return None
[ "Read the given file, if it exists.\n\n Args:\n filename: A path to a file.\n\n Returns:\n A string containing the file contents, or `None` if the file does\n not exist.\n " ]
Please provide a description of the function:def process_raw_trace(raw_trace): trace = trace_events_pb2.Trace() trace.ParseFromString(raw_trace) return ''.join(trace_events_json.TraceEventsJsonStream(trace))
[ "Processes raw trace data and returns the UI data." ]
Please provide a description of the function:def is_active(self): # If we are already active, we remain active and don't recompute this. # Otherwise, try to acquire the lock without blocking; if we get it and # we're still not active, launch a thread to check if we're active and # release the lock ...
[ "Whether this plugin is active and has any profile data to show.\n\n Detecting profile data is expensive, so this process runs asynchronously\n and the value reported by this method is the cached value and may be stale.\n\n Returns:\n Whether any run has profile data.\n " ]
Please provide a description of the function:def _run_dir(self, run): run = run.rstrip('/') if '/' not in run: run = './' + run tb_run_name, _, profile_run_name = run.rpartition('/') tb_run_directory = self.multiplexer.RunPaths().get(tb_run_name) if tb_run_directory is None: # Check...
[ "Helper that maps a frontend run name to a profile \"run\" directory.\n\n The frontend run name consists of the TensorBoard run name (aka the relative\n path from the logdir root to the directory containing the data) path-joined\n to the Profile plugin's \"run\" concept (which is a subdirectory of the\n ...
Please provide a description of the function:def generate_run_to_tools(self): self.start_grpc_stub_if_necessary() plugin_assets = self.multiplexer.PluginAssets(PLUGIN_NAME) tb_run_names_to_dirs = self.multiplexer.RunPaths() # Ensure that we also check the root logdir, even if it isn't a recognize...
[ "Generator for pairs of \"run name\" and a list of tools for that run.\n\n The \"run name\" here is a \"frontend run name\" - see _run_dir() for the\n definition of a \"frontend run name\" and how it maps to a directory of\n profile data for a specific profile \"run\". The profile plugin concept of\n \"...
Please provide a description of the function:def host_impl(self, run, tool): hosts = {} run_dir = self._run_dir(run) if not run_dir: logger.warn("Cannot find asset directory for: %s", run) return hosts tool_pattern = '*' + TOOLS[tool] try: files = tf.io.gfile.glob(os.path.join...
[ "Returns available hosts for the run and tool in the log directory.\n\n In the plugin log directory, each directory contains profile data for a\n single run (identified by the directory name), and files in the run\n directory contains data for different tools and hosts. The file that\n contains profile ...
Please provide a description of the function:def data_impl(self, request): run = request.args.get('run') tool = request.args.get('tag') host = request.args.get('host') run_dir = self._run_dir(run) # Profile plugin "run" is the last component of run dir. profile_run = os.path.basename(run_di...
[ "Retrieves and processes the tool data for a run and a host.\n\n Args:\n request: XMLHttpRequest\n\n Returns:\n A string that can be served to the frontend tool or None if tool,\n run or host is invalid.\n " ]
Please provide a description of the function:def run(logdir, run_name, initial_temperature, ambient_temperature, heat_coefficient): tf.compat.v1.reset_default_graph() tf.compat.v1.set_random_seed(0) with tf.name_scope('temperature'): # Create a mutable variable to hold the object's temperature, an...
[ "Run a temperature simulation.\n\n This will simulate an object at temperature `initial_temperature`\n sitting at rest in a large room at temperature `ambient_temperature`.\n The object has some intrinsic `heat_coefficient`, which indicates\n how much thermal conductivity it has: for instance, metals have high\...
Please provide a description of the function:def run_all(logdir, verbose=False): for initial_temperature in [270.0, 310.0, 350.0]: for final_temperature in [270.0, 310.0, 350.0]: for heat_coefficient in [0.001, 0.005]: run_name = 'temperature:t0=%g,tA=%g,kH=%g' % ( initial_temperature...
[ "Run simulations on a reasonable set of parameters.\n\n Arguments:\n logdir: the directory into which to store all the runs' data\n verbose: if true, print out each run's name as it begins\n " ]
Please provide a description of the function:def Cleanse(obj, encoding='utf-8'): if isinstance(obj, int): return obj elif isinstance(obj, float): if obj == _INFINITY: return 'Infinity' elif obj == _NEGATIVE_INFINITY: return '-Infinity' elif math.isnan(obj): return 'NaN' else...
[ "Makes Python object appropriate for JSON serialization.\n\n - Replaces instances of Infinity/-Infinity/NaN with strings.\n - Turns byte strings into unicode strings.\n - Turns sets into sorted lists.\n - Turns tuples into lists.\n\n Args:\n obj: Python data structure.\n encoding: Charset used to decode ...
Please provide a description of the function:def op(name, data, display_name=None, description=None, collections=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf if display_name is None: display_name = name summa...
[ "Create a legacy text summary op.\n\n Text data summarized via this plugin will be visible in the Text Dashboard\n in TensorBoard. The standard TensorBoard Text Dashboard will render markdown\n in the strings, and will automatically organize 1D and 2D tensors into tables.\n If a tensor with more than 2 dimensio...
Please provide a description of the function:def pb(name, data, display_name=None, description=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf try: tensor = tf.make_tensor_proto(data, dtype=tf.string) except TypeError as e: raise Value...
[ "Create a legacy text summary protobuf.\n\n Arguments:\n name: A name for the generated node. Will also serve as a series name in\n TensorBoard.\n data: A Python bytestring (of type bytes), or Unicode string. Or a numpy\n data array of those types.\n display_name: Optional name for this summary ...
Please provide a description of the function:def _GetPurgeMessage(most_recent_step, most_recent_wall_time, event_step, event_wall_time, num_expired_scalars, num_expired_histos, num_expired_comp_histos, num_expired_images, num_expired_audio): return ('D...
[ "Return the string message associated with TensorBoard purges." ]
Please provide a description of the function:def _GeneratorFromPath(path): if not path: raise ValueError('path must be a valid string') if io_wrapper.IsTensorFlowEventsFile(path): return event_file_loader.EventFileLoader(path) else: return directory_watcher.DirectoryWatcher( path, e...
[ "Create an event generator for file or directory at given path string." ]
Please provide a description of the function:def _ParseFileVersion(file_version): tokens = file_version.split('brain.Event:') try: return float(tokens[-1]) except ValueError: ## This should never happen according to the definition of file_version ## specified in event.proto. logger.warn( ...
[ "Convert the string file_version in event.proto into a float.\n\n Args:\n file_version: String file_version from event.proto\n\n Returns:\n Version number as a float.\n " ]
Please provide a description of the function:def Reload(self): with self._generator_mutex: for event in self._generator.Load(): self._ProcessEvent(event) return self
[ "Loads all events added since the last call to `Reload`.\n\n If `Reload` was never called, loads all events in the file.\n\n Returns:\n The `EventAccumulator`.\n " ]
Please provide a description of the function:def RetrievePluginAsset(self, plugin_name, asset_name): return plugin_asset_util.RetrieveAsset(self.path, plugin_name, asset_name)
[ "Return the contents of a given plugin asset.\n\n Args:\n plugin_name: The string name of a plugin.\n asset_name: The string name of an asset.\n\n Returns:\n The string contents of the plugin asset.\n\n Raises:\n KeyError: If the asset is not available.\n " ]
Please provide a description of the function:def FirstEventTimestamp(self): if self._first_event_timestamp is not None: return self._first_event_timestamp with self._generator_mutex: try: event = next(self._generator.Load()) self._ProcessEvent(event) return self._first_e...
[ "Returns the timestamp in seconds of the first event.\n\n If the first event has been loaded (either by this method or by `Reload`,\n this returns immediately. Otherwise, it will load in the first event. Note\n that this means that calling `Reload` will cause this to block until\n `Reload` has finished....
Please provide a description of the function:def PluginTagToContent(self, plugin_name): if plugin_name not in self._plugin_to_tag_to_content: raise KeyError('Plugin %r could not be found.' % plugin_name) return self._plugin_to_tag_to_content[plugin_name]
[ "Returns a dict mapping tags to content specific to that plugin.\n\n Args:\n plugin_name: The name of the plugin for which to fetch plugin-specific\n content.\n\n Raises:\n KeyError: if the plugin name is not found.\n\n Returns:\n A dict mapping tags to plugin-specific content (which ...
Please provide a description of the function:def Tags(self): return { IMAGES: self.images.Keys(), AUDIO: self.audios.Keys(), HISTOGRAMS: self.histograms.Keys(), SCALARS: self.scalars.Keys(), COMPRESSED_HISTOGRAMS: self.compressed_histograms.Keys(), TENSORS: self....
[ "Return all tags found in the value stream.\n\n Returns:\n A `{tagType: ['list', 'of', 'tags']}` dictionary.\n " ]
Please provide a description of the function:def Graph(self): graph = graph_pb2.GraphDef() if self._graph is not None: graph.ParseFromString(self._graph) return graph raise ValueError('There is no graph in this EventAccumulator')
[ "Return the graph definition, if there is one.\n\n If the graph is stored directly, return that. If no graph is stored\n directly but a metagraph is stored containing a graph, return that.\n\n Raises:\n ValueError: If there is no graph for this run.\n\n Returns:\n The `graph_def` proto.\n ...
Please provide a description of the function:def MetaGraph(self): if self._meta_graph is None: raise ValueError('There is no metagraph in this EventAccumulator') meta_graph = meta_graph_pb2.MetaGraphDef() meta_graph.ParseFromString(self._meta_graph) return meta_graph
[ "Return the metagraph definition, if there is one.\n\n Raises:\n ValueError: If there is no metagraph for this run.\n\n Returns:\n The `meta_graph_def` proto.\n " ]
Please provide a description of the function:def RunMetadata(self, tag): if tag not in self._tagged_metadata: raise ValueError('There is no run metadata with this tag name') run_metadata = config_pb2.RunMetadata() run_metadata.ParseFromString(self._tagged_metadata[tag]) return run_metadata
[ "Given a tag, return the associated session.run() metadata.\n\n Args:\n tag: A string tag associated with the event.\n\n Raises:\n ValueError: If the tag is not found.\n\n Returns:\n The metadata in form of `RunMetadata` proto.\n " ]
Please provide a description of the function:def _MaybePurgeOrphanedData(self, event): if not self.purge_orphaned_data: return ## Check if the event happened after a crash, and purge expired tags. if self.file_version and self.file_version >= 2: ## If the file_version is recent enough, use ...
[ "Maybe purge orphaned data due to a TensorFlow crash.\n\n When TensorFlow crashes at step T+O and restarts at step T, any events\n written after step T are now \"orphaned\" and will be at best misleading if\n they are included in TensorBoard.\n\n This logic attempts to determine if there is orphaned dat...
Please provide a description of the function:def _CheckForRestartAndMaybePurge(self, event): if event.HasField( 'session_log') and event.session_log.status == event_pb2.SessionLog.START: self._Purge(event, by_tags=False)
[ "Check and discard expired events using SessionLog.START.\n\n Check for a SessionLog.START event and purge all previously seen events\n with larger steps, because they are out of date. Because of supervisor\n threading, it is possible that this logic will cause the first few event\n messages to be disca...
Please provide a description of the function:def _CheckForOutOfOrderStepAndMaybePurge(self, event): if event.step < self.most_recent_step and event.HasField('summary'): self._Purge(event, by_tags=True) else: self.most_recent_step = event.step self.most_recent_wall_time = event.wall_time
[ "Check for out-of-order event.step and discard expired events for tags.\n\n Check if the event is out of order relative to the global most recent step.\n If it is, purge outdated summaries for tags that the event contains.\n\n Args:\n event: The event to use as reference. If the event is out-of-order,...
Please provide a description of the function:def _ProcessHistogram(self, tag, wall_time, step, histo): histo = self._ConvertHistogramProtoToTuple(histo) histo_ev = HistogramEvent(wall_time, step, histo) self.histograms.AddItem(tag, histo_ev) self.compressed_histograms.AddItem(tag, histo_ev, self._C...
[ "Processes a proto histogram by adding it to accumulated state." ]
Please provide a description of the function:def _CompressHistogram(self, histo_ev): return CompressedHistogramEvent( histo_ev.wall_time, histo_ev.step, compressor.compress_histogram_proto( histo_ev.histogram_value, self._compression_bps))
[ "Callback for _ProcessHistogram." ]
Please provide a description of the function:def _ProcessImage(self, tag, wall_time, step, image): event = ImageEvent(wall_time=wall_time, step=step, encoded_image_string=image.encoded_image_string, width=image.width, h...
[ "Processes an image by adding it to accumulated state." ]
Please provide a description of the function:def _ProcessAudio(self, tag, wall_time, step, audio): event = AudioEvent(wall_time=wall_time, step=step, encoded_audio_string=audio.encoded_audio_string, content_type=audio.content_type, ...
[ "Processes a audio by adding it to accumulated state." ]
Please provide a description of the function:def _ProcessScalar(self, tag, wall_time, step, scalar): sv = ScalarEvent(wall_time=wall_time, step=step, value=scalar) self.scalars.AddItem(tag, sv)
[ "Processes a simple value by adding it to accumulated state." ]
Please provide a description of the function:def _Purge(self, event, by_tags): ## Keep data in reservoirs that has a step less than event.step _NotExpired = lambda x: x.step < event.step if by_tags: def _ExpiredPerTag(value): return [getattr(self, x).FilterItems(_NotExpired, value.tag) ...
[ "Purge all events that have occurred after the given event.step.\n\n If by_tags is True, purge all events that occurred after the given\n event.step, but only for the tags that the event has. Non-sequential\n event.steps suggest that a TensorFlow restart occurred, and we discard\n the out-of-order event...
Please provide a description of the function:def Load(self): logger.debug('Loading events from %s', self._file_path) # GetNext() expects a status argument on TF <= 1.7. get_next_args = inspect.getargspec(self._reader.GetNext).args # pylint: disable=deprecated-method # First argument is self l...
[ "Loads all new events from disk as raw serialized proto bytestrings.\n\n Calling Load multiple times in a row will not 'drop' events as long as the\n return value is not iterated over.\n\n Yields:\n All event proto bytestrings in the file that have not been yielded yet.\n " ]
Please provide a description of the function:def Load(self): for record in super(EventFileLoader, self).Load(): yield event_pb2.Event.FromString(record)
[ "Loads all new events from disk.\n\n Calling Load multiple times in a row will not 'drop' events as long as the\n return value is not iterated over.\n\n Yields:\n All events in the file that have not been yielded yet.\n " ]
Please provide a description of the function:def scale_sections(sections, scaling_scope): ''' input: unscaled sections. returns: sections scaled to [0, 255] ''' new_sections = [] if scaling_scope == 'layer': for section in sections: new_sections.append(scale_image_for_display(section)) elif sc...
[]
Please provide a description of the function:def on_value_event(self, event): if not event.summary.value: logger.warn("The summary of the event lacks a value.") return # The node name property is actually a watch key, which is a concatenation # of several pieces of data. watch_key = ev...
[ "Records the summary values based on an updated message from the debugger.\n\n Logs an error message if writing the event to disk fails.\n\n Args:\n event: The Event proto to be processed.\n " ]
Please provide a description of the function:def _parse_session_run_index(self, event): metadata_string = event.log_message.message try: metadata = json.loads(metadata_string) except ValueError as e: logger.error( "Could not decode metadata string '%s' for step value: %s", ...
[ "Parses the session_run_index value from the event proto.\n\n Args:\n event: The event with metadata that contains the session_run_index.\n\n Returns:\n The int session_run_index value. Or\n constants.SENTINEL_FOR_UNDETERMINED_STEP if it could not be determined.\n " ]
Please provide a description of the function:def compress_histogram_proto(histo, bps=NORMAL_HISTOGRAM_BPS): # See also: Histogram::Percentile() in core/lib/histogram/histogram.cc if not histo.num: return [CompressedHistogramValue(b, 0.0) for b in bps] bucket = np.array(histo.bucket) bucket_limit = list(h...
[ "Creates fixed size histogram by adding compression to accumulated state.\n\n This routine transforms a histogram at a particular step by interpolating its\n variable number of buckets to represent their cumulative weight at a constant\n number of compression points. This significantly reduces the size of the\n ...
Please provide a description of the function:def compress_histogram(buckets, bps=NORMAL_HISTOGRAM_BPS): # See also: Histogram::Percentile() in core/lib/histogram/histogram.cc buckets = np.array(buckets) if not buckets.size: return [CompressedHistogramValue(b, 0.0) for b in bps] (minmin, maxmax) = (bucket...
[ "Creates fixed size histogram by adding compression to accumulated state.\n\n This routine transforms a histogram at a particular step by linearly\n interpolating its variable number of buckets to represent their cumulative\n weight at a constant number of compression points. This significantly reduces\n the si...
Please provide a description of the function:def _lerp(x, x0, x1, y0, y1): return y0 + (x - x0) * float(y1 - y0) / (x1 - x0)
[ "Affinely map from [x0, x1] onto [y0, y1]." ]
Please provide a description of the function:def is_active(self): 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 FROM Tags W...
[ "The images plugin is active iff any run has at least one relevant tag." ]
Please provide a description of the function:def _serve_image_metadata(self, request): tag = request.args.get('tag') run = request.args.get('run') sample = int(request.args.get('sample', 0)) response = self._image_response_for_run(run, tag, sample) return http_util.Respond(request, response, 'a...
[ "Given a tag and list of runs, serve a list of metadata for images.\n\n Note that the images themselves are not sent; instead, we respond with URLs\n to the images. The frontend should treat these URLs as opaque and should not\n try to parse information about them or generate them itself, as the format\n ...
Please provide a description of the function:def _image_response_for_run(self, run, tag, sample): if self._db_connection_provider: db = self._db_connection_provider() cursor = db.execute( ''' SELECT computed_time, step, CAST (T0.data AS INT) A...
[ "Builds a JSON-serializable object with information about images.\n\n Args:\n run: The name of the run.\n tag: The name of the tag the images all belong to.\n sample: The zero-indexed sample of the image for which to retrieve\n information. For instance, setting `sample` to `2` will fetch\n...
Please provide a description of the function:def _get_individual_image(self, run, tag, index, sample): if self._db_connection_provider: db = self._db_connection_provider() cursor = db.execute( ''' SELECT data FROM TensorStrings WHERE /* Skip first...
[ "\n Returns the actual image bytes for a given image.\n\n Args:\n run: The name of the run the image belongs to.\n tag: The name of the tag the images belongs to.\n index: The index of the image in the current reservoir.\n sample: The zero-indexed sample of the image to retrieve (for examp...
Please provide a description of the function:def _serve_individual_image(self, request): run = request.args.get('run') tag = request.args.get('tag') index = int(request.args.get('index')) sample = int(request.args.get('sample', 0)) data = self._get_individual_image(run, tag, index, sample) ...
[ "Serves an individual image." ]
Please provide a description of the function:def start_runs( logdir, steps, run_name, thresholds, mask_every_other_prediction=False): tf.compat.v1.reset_default_graph() tf.compat.v1.set_random_seed(42) # Create a normal distribution layer used to generate true color labels. distribution ...
[ "Generate a PR curve with precision and recall evenly weighted.\n\n Arguments:\n logdir: The directory into which to store all the runs' data.\n steps: The number of steps to run for.\n run_name: The name of the run.\n thresholds: The number of thresholds to use for PR curves.\n mask_every_other_pre...