Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def Respond(request, content, content_type, code=200, expires=0, content_encoding=None, encoding='utf-8'): mimetype = _EXTRACT_MIMETYPE_PATTERN.search(content_type).group(0) charset_match = _EXTR...
[ "Construct a werkzeug Response.\n\n Responses are transmitted to the browser with compression if: a) the browser\n supports it; b) it's sane to compress the content_type in question; and c)\n the content isn't already compressed, as indicated by the content_encoding\n parameter.\n\n Browser and proxy caching i...
Please provide a description of the function:def _find_longest_parent_path(path_set, path): # This could likely be more efficiently implemented with a trie # data-structure, but we don't want to add an extra dependency for that. while path not in path_set: if not path: return None path = os.path....
[ "Finds the longest \"parent-path\" of 'path' in 'path_set'.\n\n This function takes and returns \"path-like\" strings which are strings\n made of strings separated by os.sep. No file access is performed here, so\n these strings need not correspond to actual files in some file-system..\n This function returns th...
Please provide a description of the function:def _protobuf_value_to_string(value): value_in_json = json_format.MessageToJson(value) if value.HasField("string_value"): # Remove the quotations. return value_in_json[1:-1] return value_in_json
[ "Returns a string representation of given google.protobuf.Value message.\n\n Args:\n value: google.protobuf.Value message. Assumed to be of type 'number',\n 'string' or 'bool'.\n " ]
Please provide a description of the function:def _find_experiment_tag(self): with self._experiment_from_tag_lock: if self._experiment_from_tag is None: mapping = self.multiplexer.PluginRunToTagToContent( metadata.PLUGIN_NAME) for tag_to_content in mapping.values(): i...
[ "Finds the experiment associcated with the metadata.EXPERIMENT_TAG tag.\n\n Caches the experiment if it was found.\n\n Returns:\n The experiment or None if no such experiment is found.\n " ]
Please provide a description of the function:def _compute_experiment_from_runs(self): hparam_infos = self._compute_hparam_infos() if not hparam_infos: return None metric_infos = self._compute_metric_infos() return api_pb2.Experiment(hparam_infos=hparam_infos, met...
[ "Computes a minimal Experiment protocol buffer by scanning the runs." ]
Please provide a description of the function:def _compute_hparam_infos(self): run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent( metadata.PLUGIN_NAME) # Construct a dict mapping an hparam name to its list of values. hparams = collections.defaultdict(list) for tag_to_content i...
[ "Computes a list of api_pb2.HParamInfo from the current run, tag info.\n\n Finds all the SessionStartInfo messages and collects the hparams values\n appearing in each one. For each hparam attempts to deduce a type that fits\n all its values. Finally, sets the 'domain' of the resulting HParamInfo\n to be...
Please provide a description of the function:def _compute_hparam_info_from_values(self, name, values): # Figure out the type from the values. # Ignore values whose type is not listed in api_pb2.DataType # If all values have the same type, then that is the type used. # Otherwise, the returned type i...
[ "Builds an HParamInfo message from the hparam name and list of values.\n\n Args:\n name: string. The hparam name.\n values: list of google.protobuf.Value messages. The list of values for the\n hparam.\n\n Returns:\n An api_pb2.HParamInfo message.\n " ]
Please provide a description of the function:def _compute_metric_names(self): session_runs = self._build_session_runs_set() metric_names_set = set() run_to_tag_to_content = self.multiplexer.PluginRunToTagToContent( scalar_metadata.PLUGIN_NAME) for (run, tag_to_content) in six.iteritems(run_...
[ "Computes the list of metric names from all the scalar (run, tag) pairs.\n\n The return value is a list of (tag, group) pairs representing the metric\n names. The list is sorted in Python tuple-order (lexicographical).\n\n For example, if the scalar (run, tag) pairs are:\n (\"exp/session1\", \"loss\")\n...
Please provide a description of the function:def run(self): experiment = self._context.experiment() if experiment is None: raise error.HParamsError( "Can't find an HParams-plugin experiment data in" " the log directory. Note that it takes some time to" " scan the log dir...
[ "Handles the request specified on construction.\n\n Returns:\n An Experiment object.\n\n " ]
Please provide a description of the function:def experiment_pb( hparam_infos, metric_infos, user='', description='', time_created_secs=None): if time_created_secs is None: time_created_secs = time.time() experiment = api_pb2.Experiment( description=description, user=user, ...
[ "Creates a summary that defines a hyperparameter-tuning experiment.\n\n Args:\n hparam_infos: Array of api_pb2.HParamInfo messages. Describes the\n hyperparameters used in the experiment.\n metric_infos: Array of api_pb2.MetricInfo messages. Describes the metrics\n used in the experiment. See t...
Please provide a description of the function:def session_start_pb(hparams, model_uri='', monitor_url='', group_name='', start_time_secs=None): if start_time_secs is None: start_time_secs = time.time() session_start_info = plu...
[ "Constructs a SessionStartInfo protobuffer.\n\n Creates a summary that contains a training session metadata information.\n One such summary per training session should be created. Each should have\n a different run.\n\n Args:\n hparams: A dictionary with string keys. Describes the hyperparameter values\n ...
Please provide a description of the function:def session_end_pb(status, end_time_secs=None): if end_time_secs is None: end_time_secs = time.time() session_end_info = plugin_data_pb2.SessionEndInfo(status=status, end_time_secs=end_time_secs) return _summa...
[ "Constructs a SessionEndInfo protobuffer.\n\n Creates a summary that contains status information for a completed\n training session. Should be exported after the training session is completed.\n One such summary per training session should be created. Each should have\n a different run.\n\n Args:\n status: ...
Please provide a description of the function:def _summary(tag, hparams_plugin_data): summary = tf.compat.v1.Summary() summary.value.add( tag=tag, metadata=metadata.create_summary_metadata(hparams_plugin_data)) return summary
[ "Returns a summary holding the given HParamsPluginData message.\n\n Helper function.\n\n Args:\n tag: string. The tag to use.\n hparams_plugin_data: The HParamsPluginData message to use.\n " ]
Please provide a description of the function:def _IsDirectory(parent, item): return tf.io.gfile.isdir(os.path.join(parent, item))
[ "Helper that returns if parent/item is a directory." ]
Please provide a description of the function:def ListPlugins(logdir): plugins_dir = os.path.join(logdir, _PLUGINS_DIR) try: entries = tf.io.gfile.listdir(plugins_dir) except tf.errors.NotFoundError: return [] # Strip trailing slashes, which listdir() includes for some filesystems # for subdirectori...
[ "List all the plugins that have registered assets in logdir.\n\n If the plugins_dir does not exist, it returns an empty list. This maintains\n compatibility with old directories that have no plugins written.\n\n Args:\n logdir: A directory that was created by a TensorFlow events writer.\n\n Returns:\n a l...
Please provide a description of the function:def ListAssets(logdir, plugin_name): plugin_dir = PluginDirectory(logdir, plugin_name) try: # Strip trailing slashes, which listdir() includes for some filesystems. return [x.rstrip('/') for x in tf.io.gfile.listdir(plugin_dir)] except tf.errors.NotFoundErro...
[ "List all the assets that are available for given plugin in a logdir.\n\n Args:\n logdir: A directory that was created by a TensorFlow summary.FileWriter.\n plugin_name: A string name of a plugin to list assets for.\n\n Returns:\n A string list of available plugin assets. If the plugin subdirectory does\...
Please provide a description of the function:def RetrieveAsset(logdir, plugin_name, asset_name): asset_path = os.path.join(PluginDirectory(logdir, plugin_name), asset_name) try: with tf.io.gfile.GFile(asset_path, "r") as f: return f.read() except tf.errors.NotFoundError: raise KeyError("Asset pa...
[ "Retrieve a particular plugin asset from a logdir.\n\n Args:\n logdir: A directory that was created by a TensorFlow summary.FileWriter.\n plugin_name: The plugin we want an asset from.\n asset_name: The name of the requested asset.\n\n Returns:\n string contents of the plugin asset.\n\n Raises:\n ...
Please provide a description of the function:def distributions_impl(self, tag, run): (histograms, mime_type) = self._histograms_plugin.histograms_impl( tag, run, downsample_to=self.SAMPLE_SIZE) return ([self._compress(histogram) for histogram in histograms], mime_type)
[ "Result of the form `(body, mime_type)`, or `ValueError`." ]
Please provide a description of the function:def distributions_route(self, request): tag = request.args.get('tag') run = request.args.get('run') try: (body, mime_type) = self.distributions_impl(tag, run) code = 200 except ValueError as e: (body, mime_type) = (str(e), 'text/plain')...
[ "Given a tag and single run, return an array of compressed histograms." ]
Please provide a description of the function:def Load(self): try: for event in self._LoadInternal(): yield event except tf.errors.OpError: if not tf.io.gfile.exists(self._directory): raise DirectoryDeletedError( 'Directory %s has been permanently deleted' % self._dir...
[ "Loads new values.\n\n The watcher will load from one path at a time; as soon as that path stops\n yielding events, it will move on to the next path. We assume that old paths\n are never modified after a newer path has been written. As a result, Load()\n can be called multiple times in a row without los...
Please provide a description of the function:def _LoadInternal(self): # If the loader exists, check it for a value. if not self._loader: self._InitializeLoader() while True: # Yield all the new events in the path we're currently loading from. for event in self._loader.Load(): ...
[ "Internal implementation of Load().\n\n The only difference between this and Load() is that the latter will throw\n DirectoryDeletedError on I/O errors if it thinks that the directory has been\n permanently deleted.\n\n Yields:\n All values that have not been yielded yet.\n " ]
Please provide a description of the function:def _SetPath(self, path): old_path = self._path if old_path and not io_wrapper.IsCloudPath(old_path): try: # We're done with the path, so store its size. size = tf.io.gfile.stat(old_path).length logger.debug('Setting latest size of ...
[ "Sets the current path to watch for new events.\n\n This also records the size of the old path, if any. If the size can't be\n found, an error is logged.\n\n Args:\n path: The full path of the file to watch.\n " ]
Please provide a description of the function:def _GetNextPath(self): paths = sorted(path for path in io_wrapper.ListDirectoryAbsolute(self._directory) if self._path_filter(path)) if not paths: return None if self._path is None: return paths[0] # D...
[ "Gets the next path to load from.\n\n This function also does the checking for out-of-order writes as it iterates\n through the paths.\n\n Returns:\n The next path to load events from, or None if there are no more paths.\n " ]
Please provide a description of the function:def _HasOOOWrite(self, path): # Check the sizes of each path before the current one. size = tf.io.gfile.stat(path).length old_size = self._finalized_sizes.get(path, None) if size != old_size: if old_size is None: logger.error('File %s creat...
[ "Returns whether the path has had an out-of-order write." ]
Please provide a description of the function:def example_protos_from_path(path, num_examples=10, start_index=0, parse_examples=True, sampling_odds=1, example_class=tf.train.Ex...
[ "Returns a number of examples from the provided path.\n\n Args:\n path: A string path to the examples.\n num_examples: The maximum number of examples to return from the path.\n parse_examples: If true then parses the serialized proto from the path into\n proto objects. Defaults to True.\n sampli...
Please provide a description of the function:def call_servo(examples, serving_bundle): parsed_url = urlparse('http://' + serving_bundle.inference_address) channel = implementations.insecure_channel(parsed_url.hostname, parsed_url.port) stub = prediction_service_pb2....
[ "Send an RPC request to the Servomatic prediction service.\n\n Args:\n examples: A list of examples that matches the model spec.\n serving_bundle: A `ServingBundle` object that contains the information to\n make the serving request.\n\n Returns:\n A ClassificationResponse or RegressionResponse proto...
Please provide a description of the function:def migrate_value(value): handler = { 'histo': _migrate_histogram_value, 'image': _migrate_image_value, 'audio': _migrate_audio_value, 'simple_value': _migrate_scalar_value, }.get(value.WhichOneof('value')) return handler(value) if handler el...
[ "Convert `value` to a new-style value, if necessary and possible.\n\n An \"old-style\" value is a value that uses any `value` field other than\n the `tensor` field. A \"new-style\" value is a value that uses the\n `tensor` field. TensorBoard continues to support old-style values on\n disk; this method converts ...
Please provide a description of the function:def get_plugin_apps(self): return { '/infer': self._infer, '/update_example': self._update_example, '/examples_from_path': self._examples_from_path_handler, '/sprite': self._serve_sprite, '/duplicate_example': self._duplicate_...
[ "Obtains a mapping between routes and handlers. Stores the logdir.\n\n Returns:\n A mapping between routes and handlers (functions that respond to\n requests).\n " ]
Please provide a description of the function:def _examples_from_path_handler(self, request): examples_count = int(request.args.get('max_examples')) examples_path = request.args.get('examples_path') sampling_odds = float(request.args.get('sampling_odds')) self.example_class = (tf.train.SequenceExamp...
[ "Returns JSON of the specified examples.\n\n Args:\n request: A request that should contain 'examples_path' and 'max_examples'.\n\n Returns:\n JSON of up to max_examlpes of the examples in the path.\n " ]
Please provide a description of the function:def _update_example(self, request): if request.method != 'POST': return http_util.Respond(request, {'error': 'invalid non-POST request'}, 'application/json', code=405) example_json = request.form['example'] index = int(re...
[ "Updates the specified example.\n\n Args:\n request: A request that should contain 'index' and 'example'.\n\n Returns:\n An empty response.\n " ]
Please provide a description of the function:def _duplicate_example(self, request): index = int(request.args.get('index')) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) new_exampl...
[ "Duplicates the specified example.\n\n Args:\n request: A request that should contain 'index'.\n\n Returns:\n An empty response.\n " ]
Please provide a description of the function:def _delete_example(self, request): index = int(request.args.get('index')) if index >= len(self.examples): return http_util.Respond(request, {'error': 'invalid index provided'}, 'application/json', code=400) del self.exam...
[ "Deletes the specified example.\n\n Args:\n request: A request that should contain 'index'.\n\n Returns:\n An empty response.\n " ]
Please provide a description of the function:def _parse_request_arguments(self, request): inference_addresses = request.args.get('inference_address').split(',') model_names = request.args.get('model_name').split(',') model_versions = request.args.get('model_version').split(',') model_signatures = r...
[ "Parses comma separated request arguments\n\n Args:\n request: A request that should contain 'inference_address', 'model_name',\n 'model_version', 'model_signature'.\n\n Returns:\n A tuple of lists for model parameters\n " ]
Please provide a description of the function:def _infer(self, request): label_vocab = inference_utils.get_label_vocab( request.args.get('label_vocab_path')) try: if request.method != 'GET': logger.error('%s requests are forbidden.', request.method) return http_util.Respond(requ...
[ "Returns JSON for the `vz-line-chart`s for a feature.\n\n Args:\n request: A request that should contain 'inference_address', 'model_name',\n 'model_type, 'model_version', 'model_signature' and 'label_vocab_path'.\n\n Returns:\n A list of JSON objects, one for each chart.\n " ]
Please provide a description of the function:def _eligible_features_from_example_handler(self, request): features_list = inference_utils.get_eligible_features( self.examples[0: NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS) return http_util.Respond(request, features_list, 'application/json')
[ "Returns a list of JSON objects for each feature in the example.\n\n Args:\n request: A request for features.\n\n Returns:\n A list with a JSON object for each feature.\n Numeric features are represented as {name: observedMin: observedMax:}.\n Categorical features are repesented as {name: ...
Please provide a description of the function:def _infer_mutants_handler(self, request): try: if request.method != 'GET': logger.error('%s requests are forbidden.', request.method) return http_util.Respond(request, {'error': 'invalid non-GET request'}, 'app...
[ "Returns JSON for the `vz-line-chart`s for a feature.\n\n Args:\n request: A request that should contain 'feature_name', 'example_index',\n 'inference_address', 'model_name', 'model_type', 'model_version', and\n 'model_signature'.\n\n Returns:\n A list of JSON objects, one for each c...
Please provide a description of the function:def _serve_asset(self, path, gzipped_asset_bytes, request): mimetype = mimetypes.guess_type(path)[0] or 'application/octet-stream' return http_util.Respond( request, gzipped_asset_bytes, mimetype, content_encoding='gzip')
[ "Serves a pre-gzipped static asset from the zip file." ]
Please provide a description of the function:def _serve_environment(self, request): return http_util.Respond( request, { 'data_location': self._logdir or self._db_uri, 'mode': 'db' if self._db_uri else 'logdir', 'window_title': self._window_title, }, ...
[ "Serve a JSON object containing some base properties used by the frontend.\n\n * data_location is either a path to a directory or an address to a\n database (depending on which mode TensorBoard is running in).\n * window_title is the title of the TensorBoard web page.\n " ]
Please provide a description of the function:def _serve_runs(self, request): if self._db_connection_provider: db = self._db_connection_provider() cursor = db.execute(''' SELECT run_name, started_time IS NULL as started_time_nulls_last, started_time FROM...
[ "Serve a JSON array of run names, ordered by run started time.\n\n Sort order is by started time (aka first event time) with empty times sorted\n last, and then ties are broken by sorting on the run name.\n " ]
Please provide a description of the function:def _serve_experiments(self, request): results = self.list_experiments_impl() return http_util.Respond(request, results, 'application/json')
[ "Serve a JSON array of experiments. Experiments are ordered by experiment\n started time (aka first event time) with empty times sorted last, and then\n ties are broken by sorting on the experiment name.\n " ]
Please provide a description of the function:def _serve_experiment_runs(self, request): results = [] if self._db_connection_provider: exp_id = request.args.get('experiment') runs_dict = collections.OrderedDict() db = self._db_connection_provider() cursor = db.execute(''' SE...
[ "Serve a JSON runs of an experiment, specified with query param\n `experiment`, with their nested data, tag, populated. Runs returned are\n ordered by started time (aka first event time) with empty times sorted last,\n and then ties are broken by sorting on the run name. Tags are sorted by\n its name, d...
Please provide a description of the function:def define_flags(self, parser): parser.add_argument( '--logdir', metavar='PATH', type=str, default='', help='''\ Directory where TensorBoard will look to find TensorFlow event files that it can display. TensorBoard will recurs...
[ "Adds standard TensorBoard CLI flags to parser." ]
Please provide a description of the function:def fix_flags(self, flags): FlagsError = base_plugin.FlagsError if flags.version_tb: pass elif flags.inspect: if flags.logdir and flags.event_file: raise FlagsError( 'Must specify either --logdir or --event_file, but not both....
[ "Fixes standard TensorBoard CLI flags to parser." ]
Please provide a description of the function:def put(self, message): with self._outgoing_lock: self._outgoing.append(message) self._outgoing_counter += 1 # Check to see if there are pending queues waiting for the item. if self._outgoing_counter in self._outgoing_pending_queues: ...
[ "Put a message into the outgoing message stack.\n\n Outgoing message will be stored indefinitely to support multi-users.\n " ]
Please provide a description of the function:def get(self, pos): if pos <= 0: raise ValueError('Invalid pos %d: pos must be > 0' % pos) with self._outgoing_lock: if self._outgoing_counter >= pos: # If the stack already has the requested position, return the value # immediately. ...
[ "Get message(s) from the outgoing message stack.\n\n Blocks until an item at stack position pos becomes available.\n This method is thread safe.\n\n Args:\n pos: An int specifying the top position of the message stack to access.\n For example, if the stack counter is at 3 and pos == 2, then t...
Please provide a description of the function:def run(): step = tf.compat.v1.placeholder(tf.float32, shape=[]) with tf.name_scope('loss'): # Specify 2 different loss values, each tagged differently. summary_lib.scalar('foo', tf.pow(0.9, step)) summary_lib.scalar('bar', tf.pow(0.85, step + 2)) # ...
[ "Run custom scalar demo and generate event files." ]
Please provide a description of the function:def load(self, context): try: # pylint: disable=g-import-not-at-top,unused-import import tensorflow except ImportError: return # pylint: disable=line-too-long,g-import-not-at-top from tensorboard.plugins.interactive_inference.interactiv...
[ "Returns the plugin, if possible.\n\n Args:\n context: The TBContext flags.\n\n Returns:\n A InteractiveInferencePlugin instance or None if it couldn't be loaded.\n " ]
Please provide a description of the function:def visualize_embeddings(summary_writer, config): logdir = summary_writer.get_logdir() # Sanity checks. if logdir is None: raise ValueError('Summary writer must have a logdir') # Saving the config file in the logdir. config_pbtxt = _text_format.MessageToSt...
[ "Stores a config file used by the embedding projector.\n\n Args:\n summary_writer: The summary writer used for writing events.\n config: `tf.contrib.tensorboard.plugins.projector.ProjectorConfig`\n proto that holds the configuration for the projector such as paths to\n checkpoint files and metadata...
Please provide a description of the function:def _wrap_define_function(original_function): def wrapper(*args, **kwargs): has_old_names = False for old_name, new_name in _six.iteritems(_RENAMED_ARGUMENTS): if old_name in kwargs: has_old_names = True ...
[ "Wraps absl.flags's define functions so tf.flags accepts old names.", "Wrapper function that turns old keyword names to new ones." ]
Please provide a description of the function:def run_tag_from_session_and_metric(session_name, metric_name): assert isinstance(session_name, six.string_types) assert isinstance(metric_name, api_pb2.MetricName) # os.path.join() will append a final slash if the group is empty; it seems # like multiplexer.Tenso...
[ "Returns a (run,tag) tuple storing the evaluations of the specified metric.\n\n Args:\n session_name: str.\n metric_name: MetricName protobuffer.\n Returns: (run, tag) tuple.\n " ]
Please provide a description of the function:def last_metric_eval(multiplexer, session_name, metric_name): try: run, tag = run_tag_from_session_and_metric(session_name, metric_name) tensor_events = multiplexer.Tensors(run=run, tag=tag) except KeyError as e: raise KeyError( 'Can\'t find metric...
[ "Returns the last evaluations of the given metric at the given session.\n\n Args:\n multiplexer: The EventMultiplexer instance allowing access to\n the exported summary data.\n session_name: String. The session name for which to get the metric\n evaluations.\n metric_name: api_pb2.MetricName...
Please provide a description of the function:def index_impl(self): if self._db_connection_provider: # Read tags from the database. db = self._db_connection_provider() cursor = db.execute(''' SELECT Tags.tag_name, Tags.display_name, Runs.run_name F...
[ "Return {runName: {tagName: {displayName: ..., description: ...}}}." ]
Please provide a description of the function:def scalars_impl(self, tag, run, experiment, output_format): if self._db_connection_provider: db = self._db_connection_provider() # We select for steps greater than -1 because the writer inserts # placeholder rows en masse. The check for step filte...
[ "Result of the form `(body, mime_type)`." ]
Please provide a description of the function:def _get_value(self, scalar_data_blob, dtype_enum): tensorflow_dtype = tf.DType(dtype_enum) buf = np.frombuffer(scalar_data_blob, dtype=tensorflow_dtype.as_numpy_dtype) return np.asscalar(buf)
[ "Obtains value for scalar event given blob and dtype enum.\n\n Args:\n scalar_data_blob: The blob obtained from the database.\n dtype_enum: The enum representing the dtype.\n\n Returns:\n The scalar value.\n " ]
Please provide a description of the function:def scalars_route(self, request): # TODO: return HTTP status code for malformed requests tag = request.args.get('tag') run = request.args.get('run') experiment = request.args.get('experiment') output_format = request.args.get('format') (body, mim...
[ "Given a tag and single run, return array of ScalarEvents." ]
Please provide a description of the function:def AddRun(self, path, name=None): name = name or path accumulator = None with self._accumulators_mutex: if name not in self._accumulators or self._paths[name] != path: if name in self._paths and self._paths[name] != path: # TODO(@dan...
[ "Add a run to the multiplexer.\n\n If the name is not specified, it is the same as the path.\n\n If a run by that name exists, and we are already watching the right path,\n do nothing. If we are watching a different path, replace the event\n accumulator.\n\n If `Reload` has been called, it will `...
Please provide a description of the function:def AddRunsFromDirectory(self, path, name=None): logger.info('Starting AddRunsFromDirectory: %s', path) for subdir in io_wrapper.GetLogdirSubdirectories(path): logger.info('Adding run from directory %s', subdir) rpath = os.path.relpath(subdir, path) ...
[ "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 If path is a directory, load event files in the directory (if any exist) and\n recursi...
Please provide a description of the function:def Reload(self): 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 = list(...
[ "Call `Reload` on every `EventAccumulator`.", "Keeps reloading accumulators til none are left." ]
Please provide a description of the function:def PluginAssets(self, plugin_name): with self._accumulators_mutex: # To avoid nested locks, we construct a copy of the run-accumulator map items = list(six.iteritems(self._accumulators)) return {run: accum.PluginAssets(plugin_name) for run, accum i...
[ "Get index of runs and assets for a given plugin.\n\n Args:\n plugin_name: Name of the plugin we are checking for.\n\n Returns:\n A dictionary that maps from run_name to a list of plugin\n assets for that run.\n " ]
Please provide a description of the function:def RetrievePluginAsset(self, run, plugin_name, asset_name): accumulator = self.GetAccumulator(run) return accumulator.RetrievePluginAsset(plugin_name, asset_name)
[ "Return the contents for a specific plugin asset from a run.\n\n Args:\n run: The string name of the run.\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 as...
Please provide a description of the function:def Scalars(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.Scalars(tag)
[ "Retrieve the scalar events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the give...
Please provide a description of the function:def RunMetadata(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.RunMetadata(tag)
[ "Get the session.run() metadata associated with a TensorFlow run and tag.\n\n Args:\n run: A string name of a TensorFlow run.\n tag: A string name of the tag associated with a particular session.run().\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for the\n ...
Please provide a description of the function:def Audio(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.Audio(tag)
[ "Retrieve the audio events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the given...
Please provide a description of the function:def Tensors(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.Tensors(tag)
[ "Retrieve the tensor events associated with a run and tag.\n\n Args:\n run: A string name of the run for which values are retrieved.\n tag: A string name of the tag for which values are retrieved.\n\n Raises:\n KeyError: If the run is not found, or the tag is not available for\n the give...
Please provide a description of the function:def PluginRunToTagToContent(self, plugin_name): mapping = {} for run in self.Runs(): try: tag_to_content = self.GetAccumulator(run).PluginTagToContent( plugin_name) except KeyError: # This run lacks content for the plugin....
[ "Returns a 2-layer dictionary of the form {run: {tag: content}}.\n\n The `content` referred above is the content field of the PluginData proto\n for the specified plugin within a Summary.Value proto.\n\n Args:\n plugin_name: The name of the plugin for which to fetch content.\n\n Returns:\n A d...
Please provide a description of the function:def SummaryMetadata(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.SummaryMetadata(tag)
[ "Return the summary metadata for the given tag on the given run.\n\n Args:\n run: A string name of the run for which summary metadata is to be\n retrieved.\n tag: A string name of the tag whose summary metadata is to be\n retrieved.\n\n Raises:\n KeyError: If the run is not found,...
Please provide a description of the function:def Runs(self): with self._accumulators_mutex: # To avoid nested locks, we construct a copy of the run-accumulator map items = list(six.iteritems(self._accumulators)) return {run_name: accumulator.Tags() for run_name, accumulator in items}
[ "Return all the run names in the `EventMultiplexer`.\n\n Returns:\n ```\n {runName: { scalarValues: [tagA, tagB, tagC],\n graph: true, meta_graph: true}}\n ```\n " ]
Please provide a description of the function:def text(name, data, step=None, description=None): summary_metadata = metadata.create_summary_metadata( display_name=None, description=description) # TODO(https://github.com/tensorflow/tensorboard/issues/2109): remove fallback summary_scope = ( getattr(t...
[ "Write a text summary.\n\n Arguments:\n name: A name for this summary. The summary tag used for TensorBoard will\n be this name prefixed by any active name scopes.\n data: A UTF-8 string tensor value.\n step: Explicit `int64`-castable monotonic step value for this summary. If\n omitted, this def...
Please provide a description of the function:def text_pb(tag, data, description=None): try: tensor = tensor_util.make_tensor_proto(data, dtype=np.object) except TypeError as e: raise TypeError('tensor must be of type string', e) summary_metadata = metadata.create_summary_metadata( display_name=No...
[ "Create a text tf.Summary protobuf.\n\n Arguments:\n tag: String tag for the summary.\n data: A Python bytestring (of type bytes), a Unicode string, or a numpy data\n array of those types.\n description: Optional long-form description for this summary, as a `str`.\n Markdown is supported. Defaul...
Please provide a description of the function:def run_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(), ...
[ "Initializes flags and calls main()." ]
Please provide a description of the function:def create_summary_metadata(display_name, description): content = plugin_data_pb2.ImagePluginData(version=PROTO_VERSION) metadata = summary_pb2.SummaryMetadata( display_name=display_name, summary_description=description, plugin_data=summary_pb2.Summa...
[ "Create a `summary_pb2.SummaryMetadata` proto for image plugin data.\n\n Returns:\n A `summary_pb2.SummaryMetadata` protobuf object.\n " ]
Please provide a description of the function:def op(name, audio, sample_rate, labels=None, max_outputs=3, encoding=None, display_name=None, description=None, collections=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import t...
[ "Create a legacy audio summary op for use in a TensorFlow graph.\n\n Arguments:\n name: A unique name for the generated summary node.\n audio: A `Tensor` representing audio data with shape `[k, t, c]`,\n where `k` is the number of audio clips, `t` is the number of\n frames, and `c` is the number of...
Please provide a description of the function:def pb(name, audio, sample_rate, labels=None, max_outputs=3, encoding=None, display_name=None, description=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf...
[ "Create a legacy audio summary protobuf.\n\n This behaves as if you were to create an `op` with the same arguments\n (wrapped with constant tensors where appropriate) and then execute\n that summary op in a TensorFlow session.\n\n Arguments:\n name: A unique name for the generated summary node.\n audio: A...
Please provide a description of the function:def op( name, labels, predictions, num_thresholds=None, weights=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 i...
[ "Create a PR curve summary op for a single binary classifier.\n\n Computes true/false positive/negative values for the given `predictions`\n against the ground truth `labels`, against a list of evenly distributed\n threshold values in `[0, 1]` of length `num_thresholds`.\n\n Each number in `predictions`, a floa...
Please provide a description of the function:def pb(name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None): # TODO(nickfelt): remove on-demand imports once dep situation is fixed. import tensorflow.compat.v1 as tf if num_thr...
[ "Create a PR curves summary protobuf.\n\n Arguments:\n name: A name for the generated node. Will also serve as a series name in\n TensorBoard.\n labels: The ground truth values. A bool numpy array.\n predictions: A float32 numpy array whose values are in the range `[0, 1]`.\n Dimensions must...
Please provide a description of the function:def streaming_op(name, labels, predictions, num_thresholds=None, weights=None, metrics_collections=None, updates_collections=None, display_name=None, ...
[ "Computes a precision-recall curve summary across batches of data.\n\n This function is similar to op() above, but can be used to compute the PR\n curve across multiple batches of labels and predictions, in the same style\n as the metrics found in tf.metrics.\n\n This function creates multiple local variables f...
Please provide a description of the function: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): # TODO(nickfelt):...
[ "Create an op that collects data for visualizing PR curves.\n\n Unlike the op above, this one avoids computing precision, recall, and the\n intermediate counts. Instead, it accepts those tensors as arguments and\n relies on the caller to ensure that the calculations are correct (and the\n counts yield the provi...
Please provide a description of the function: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): # TODO(nickfelt): remove on-demand impo...
[ "Create a PR curves summary protobuf from raw data values.\n\n Args:\n name: A tag attached to the summary. Used by TensorBoard for organization.\n true_positive_counts: A rank-1 numpy array of true positive counts. Must\n contain `num_thresholds` elements and be castable to float32.\n false_positi...
Please provide a description of the function: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): # TODO...
[ "A private helper method for generating a tensor summary.\n\n We use a helper method instead of having `op` directly call `raw_data_op`\n to prevent the scope of `raw_data_op` from being embedded within `op`.\n\n Arguments are the same as for raw_data_op.\n\n Returns:\n A tensor summary that collects data fo...
Please provide a description of the function:def run(self): run, tag = metrics.run_tag_from_session_and_metric( self._request.session_name, self._request.metric_name) body, _ = self._scalars_plugin_instance.scalars_impl( tag, run, None, scalars_plugin.OutputFormat.JSON) return body
[ "Executes the request.\n\n Returns:\n An array of tuples representing the metric evaluations--each of the form\n (<wall time in secs>, <training step>, <metric value>).\n " ]
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 WHERE Ta...
[ "This plugin is active iff any run has at least one histograms tag." ]
Please provide a description of the function:def histograms_impl(self, tag, run, downsample_to=None): if self._db_connection_provider: # Serve data from the database. db = self._db_connection_provider() cursor = db.cursor() # Prefetch the tag ID matching this run and tag. cursor.e...
[ "Result of the form `(body, mime_type)`, or `ValueError`.\n\n At most `downsample_to` events will be returned. If this value is\n `None`, then no downsampling will be performed.\n " ]
Please provide a description of the function:def _get_values(self, data_blob, dtype_enum, shape_string): buf = np.frombuffer(data_blob, dtype=tf.DType(dtype_enum).as_numpy_dtype) return buf.reshape([int(i) for i in shape_string.split(',')]).tolist()
[ "Obtains values for histogram data given blob and dtype enum.\n Args:\n data_blob: The blob obtained from the database.\n dtype_enum: The enum representing the dtype.\n shape_string: A comma-separated string of numbers denoting shape.\n Returns:\n The histogram values as a list served to t...
Please provide a description of the function:def histograms_route(self, request): 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 ValueError as e: (body...
[ "Given a tag and single run, return array of histogram values." ]
Please provide a description of the function:def _lazily_initialize(self): # 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() with graph.as_defaul...
[ "Initialize the graph and session, if this has not yet been done." ]
Please provide a description of the function:def _get_scalars_plugin(self): if scalars_metadata.PLUGIN_NAME in self._plugin_name_to_instance: # The plugin is registered. return self._plugin_name_to_instance[scalars_metadata.PLUGIN_NAME] # The plugin is not yet registered. return None
[ "Tries to get the scalars plugin.\n\n Returns:\n The scalars plugin. Or None if it is not yet registered.\n " ]
Please provide a description of the function:def is_active(self): if not self._multiplexer: return False scalars_plugin_instance = self._get_scalars_plugin() if not (scalars_plugin_instance and scalars_plugin_instance.is_active()): return False # This plugin is active if a...
[ "This plugin is active if 2 conditions hold.\n\n 1. The scalars plugin is registered and active.\n 2. There is a custom layout for the dashboard.\n\n Returns: A boolean. Whether the plugin is active.\n " ]
Please provide a description of the function:def download_data_impl(self, run, tag, response_format): scalars_plugin_instance = self._get_scalars_plugin() if not scalars_plugin_instance: raise ValueError(('Failed to respond to request for /download_data. ' 'The scalars plugin ...
[ "Provides a response for downloading scalars data for a data series.\n\n Args:\n run: The run.\n tag: The specific tag.\n response_format: A string. One of the values of the OutputFormat enum of\n the scalar plugin.\n\n Raises:\n ValueError: If the scalars plugin is not registered.\...
Please provide a description of the function:def scalars_route(self, request): # TODO: return HTTP status code for malformed requests tag_regex_string = request.args.get('tag') run = request.args.get('run') mime_type = 'application/json' try: body = self.scalars_impl(run, tag_regex_strin...
[ "Given a tag regex and single run, return ScalarEvents.\n\n This route takes 2 GET params:\n run: A run string to find tags for.\n tag: A string that is a regex used to find matching tags.\n The response is a JSON object:\n {\n // Whether the regular expression is valid. Also false if empty.\n ...
Please provide a description of the function:def scalars_impl(self, run, tag_regex_string): if not tag_regex_string: # The user provided no regex. return { _REGEX_VALID_PROPERTY: False, _TAG_TO_EVENTS_PROPERTY: {}, } # Construct the regex. try: regex = re.co...
[ "Given a tag regex and single run, return ScalarEvents.\n\n Args:\n run: A run string.\n tag_regex_string: A regular expression that captures portions of tags.\n\n Raises:\n ValueError: if the scalars plugin is not registered.\n\n Returns:\n A dictionary that is the JSON-able response.\...
Please provide a description of the function:def layout_route(self, request): r body = self.layout_impl() return http_util.Respond(request, body, 'application/json')
[ "Fetches the custom layout specified by the config file in the logdir.\n\n If more than 1 run contains a layout, this method merges the layouts by\n merging charts within individual categories. If 2 categories with the same\n name are found, the charts within are merged. The merging is based on the\n or...
Please provide a description of the function:def make_table_row(contents, tag='td'): columns = ('<%s>%s</%s>\n' % (tag, s, tag) for s in contents) return '<tr>\n' + ''.join(columns) + '</tr>\n'
[ "Given an iterable of string contents, make a table row.\n\n Args:\n contents: An iterable yielding strings.\n tag: The tag to place contents in. Defaults to 'td', you might want 'th'.\n\n Returns:\n A string containing the content strings, organized into a table row.\n\n Example: make_table_row(['one',...
Please provide a description of the function:def make_table(contents, headers=None): if not isinstance(contents, np.ndarray): raise ValueError('make_table contents must be a numpy ndarray') if contents.ndim not in [1, 2]: raise ValueError('make_table requires a 1d or 2d numpy array, was %dd' % ...
[ "Given a numpy ndarray of strings, concatenate them into a html table.\n\n Args:\n contents: A np.ndarray of strings. May be 1d or 2d. In the 1d case, the\n table is laid out vertically (i.e. row-major).\n headers: A np.ndarray or list of string header names for the table.\n\n Returns:\n A string co...
Please provide a description of the function:def reduce_to_2d(arr): if not isinstance(arr, np.ndarray): raise ValueError('reduce_to_2d requires a numpy.ndarray') ndims = len(arr.shape) if ndims < 2: raise ValueError('reduce_to_2d requires an array of dimensionality >=2') # slice(None) is equivalent ...
[ "Given a np.npdarray with nDims > 2, reduce it to 2d.\n\n It does this by selecting the zeroth coordinate for every dimension greater\n than two.\n\n Args:\n arr: a numpy ndarray of dimension at least 2.\n\n Returns:\n A two-dimensional subarray from the input array.\n\n Raises:\n ValueError: If the a...
Please provide a description of the function:def text_array_to_html(text_arr): if not text_arr.shape: # It is a scalar. No need to put it in a table, just apply markdown return plugin_util.markdown_to_safe_html(np.asscalar(text_arr)) warning = '' if len(text_arr.shape) > 2: warning = plugin_util.ma...
[ "Take a numpy.ndarray containing strings, and convert it into html.\n\n If the ndarray contains a single scalar string, that string is converted to\n html via our sanitized markdown parser. If it contains an array of strings,\n the strings are individually converted to html and then composed into a table\n usin...
Please provide a description of the function:def process_string_tensor_event(event): 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, }
[ "Convert a TensorEvent into a JSON-compatible response." ]
Please provide a description of the function:def is_active(self): if not self._multiplexer: return False if self._index_cached is not None: # If we already have computed the index, use it to determine whether # the plugin should be active, and if so, return immediately. if any(self...
[ "Determines whether this plugin is active.\n\n This plugin is only active if TensorBoard sampled any text summaries.\n\n Returns:\n Whether this plugin is active.\n " ]
Please provide a description of the function:def _maybe_launch_index_impl_thread(self): # Try to acquire the lock for computing index_impl(), without blocking. if self._index_impl_lock.acquire(False): # We got the lock. Start the thread, which will unlock the lock when done. self._index_impl_th...
[ "Attempts to launch a thread to compute index_impl().\n\n This may not launch a new thread if one is already running to compute\n index_impl(); in that case, this function is a no-op.\n " ]
Please provide a description of the function:def _async_index_impl(self): 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 = time.time() - start ...
[ "Computes index_impl() asynchronously on a separate thread." ]
Please provide a description of the function:def create_summary_metadata(display_name, description, num_thresholds): pr_curve_plugin_data = plugin_data_pb2.PrCurvePluginData( version=PROTO_VERSION, num_thresholds=num_thresholds) content = pr_curve_plugin_data.SerializeToString() return summary_pb2.Summar...
[ "Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data.\n\n Arguments:\n display_name: The display name used in TensorBoard.\n description: The description to show in TensorBoard.\n num_thresholds: The number of thresholds to use for PR curves.\n\n Returns:\n A `summary_pb2.SummaryMet...